第一次寫python

這是一個在BJDP上學習Coding Kata的時候用到的一個練習,原來打算用Java寫的,但是一想正好是學習的好機會。

就用Python了。第一次,寫的有些復雜。

這個題目是關于購買圖書的打折信息的。

題目來源:

http://codingdojo.org/cgi-bin/wiki.pl?KataPotter

  1 class Strategy:
  2     def __init__(self, items):
  3         self.items = items;
  4         self.rate = self.get_discount_rate();
  5    
  6     def get_discount_rate(self):
  7         if len(self.items) == 5:
  8             return 0.75;
  9         if len(self.items) == 4:
 10             return 0.8;
 11         if len(self.items) == 3:
 12             return 0.9;
 13         if len(self.items) == 2:
 14             return 0.95;
 15         return 1.0;
 16 
 17     def get_price(self):
 18         return self.total_price() * self.rate;
 19 
 20     def total_price(self):
 21         price = 0.0;
 22         for item in self.items:
 23             price += item.book.price;
 24         return price;
 25 
 26     def count(self):
 27         return len(self.items);
 28     
 29 
 30 class StrategyOptimizer:
 31     def optimize(self, strategies):
 32         found = False;
 33         while True:
 34             found = self.replace_53_with_44(strategies);
 35             if not found:
 36                 break;
 37         return strategies;
 38 
 39     def replace_53_with_44(self, strategies):
 40         strategyMap = {};
 41         strategyMap.clear();
 42         for i in range(0, len(strategies)):
 43             strategy = strategies[i];
 44             strategyMap[strategy.count()] = i;
 45 
 46         if (strategyMap != None and len(strategyMap) != 0):
 47             if (strategyMap.get(5, None) != None and strategyMap.get(3, None) != None):
 48                 self.move_book(strategies[strategyMap[5]], strategies[strategyMap[3]]);
 49                 return True;
 50         return False;
 51 
 52     def move_book(self, source, dest):
 53         item = self.findAnyDiff(source, dest);
 54         if item == None:
 55             return;
 56         source.items.remove(item);
 57         source.rate = source.get_discount_rate();
 58         dest.items.extend([item]);
 59         dest.rate = source.get_discount_rate();
 60         return;
 61     
 62     def findAnyDiff(self, source, dest):
 63         for item in source.items:
 64             if item not in dest.items:
 65                 return item;
 66         return None;
 67 
 68 class Book:
 69     def __init__(self, index, name, price):
 70         self.index = index;
 71         self.name = name
 72         self.price = price
 73 
 74 class Item:
 75     def __init__(self, book, count):
 76         self.book = book
 77         self.count = count
 78 
 79 class Cart:
 80     items = [];
 81     def add_item(self, item):
 82         self.items.append(item);
 83 
 84 def pick_most_books(cart):
 85     items = [];
 86     for i in range(0, len(cart.items)):
 87         item = cart.items[i];
 88         if item.count == 0:
 89             continue;
 90         items.append(Item(item.book, 1));
 91         cart.items[i].count -= 1;
 92     return items;
 93 
 94 def is_empty(cart):
 95     for item in cart.items:
 96         if item.count > 0:
 97             return False;
 98     return True;
 99 
100 def count_price(strategies):
101     price = 0;
102     for s in strategies:
103         price += s.get_price();
104     return price;
105 
106 def find_best_solution(cart):
107     strategies = [];
108     price = 0.0;
109     while not is_empty(cart):
110         items = pick_most_books(cart);
111         strategy = Strategy(items);
112         strategies.append(strategy);
113     return strategies;
114 
115 def count_best_price(cart):
116     strategies = find_best_solution(cart);
117     so = StrategyOptimizer();
118     strategies = so.optimize(strategies)
119     price = count_price(strategies);
120     print(price);
121 
122 if __name__ == '__main__':
123     item_1 = Item(Book("#1.", "Philosophy Stone", 8), 2);
124     item_2 = Item(Book("#2.", "Secret Chamber", 8), 2);
125     item_3 = Item(Book("#3.", "Prisoner of Azkaban", 8), 2);
126     item_4 = Item(Book("#4.", "Goblet of Fire", 8), 1);
127     item_5 = Item(Book("#5.", "The Order of Phoenix", 8), 1);
128     
129     cart = Cart();
130     cart.add_item(item_1);
131     cart.add_item(item_2);
132     cart.add_item(item_3);
133     cart.add_item(item_4);
134     cart.add_item(item_5);
135 
136     count_best_price(cart);

?

轉載于:https://www.cnblogs.com/stephen-wang/p/3229953.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/274120.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/274120.shtml
英文地址,請注明出處:http://en.pswp.cn/news/274120.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Android 第八課 創建自定義控件

常用控件和布局的繼承結構,如下圖: (待續。。。。) 所有的控件都是直接或間接繼承自View的,所用的所有布局都是直接或間接繼承自ViewGroup的,View是Android中最基本的一種UI組件,它可以在屏幕上…

figma下載_搬到Figma對我意味著什么

figma下載A couple of years ago, amidst the boom of new design and prototyping software, I was pretty reluctant to fight on the Figma/Sketch cold war. I was working on a relatively small design team and, after years helping to design products, well sold on …

解決IE中img.onload失效的方法

解決IE中img.onload失效的方法 - CoffeeCats IT Blog - IT博客http://www.cnitblog.com/CoffeeCat/archive/2008/02/01/39533.htmlFirefox、Google Chrome不存在問題!為什么onload沒有被IE調用呢?因為IE會緩存圖片,第2次加載的圖片&#xff0…

Android 第九課 常用控件-------ListView

ListView允許用戶通過手指上下滑動的方式將屏幕外的數據滾動到屏幕內,同時屏幕上原有數據將會滾動出屏幕。 1、ListView簡單用法 如何將ListView將你要顯示的大量內容關聯起來呢?這是個很重要的問題。 1、首先我們必須先將數據提供好,因為你的…

Singleton patterns 單件(創建型模式)

1、模式分類 1.1 從目的來看: ? – 創建型(Creational)模式:負責對象創建。 ? – 結構型(Structural)模式:處理類與對象間的組合。 ? – 行為型(Behavioral&…

Android 第十一課 SQlite 數據庫存儲

Android 為了讓我們能夠更加方便的管理數據庫,特意提供了一個SQLiteOpenHelper幫助類,通過借助這個類就可以非常簡單的對數據庫進行創建和升級。 SQLiteOpenHelper是一個抽象類,我們要創建一個自己的幫助類去繼承它。SQLiteOpenHelper有兩個抽…

淺析SQL Server 2005中的主動式通知機制

一、引言 在開發多人同時訪問的Web應用程序(其實不只這類程序)時,開發人員往往會在緩存策略的設計上狠下功夫。這是因為,如果將這種環境下不常變更的數據臨時存放在應用程序服務器或是用戶機器上的話,可以避免頻繁地往…

Android 第十二課 使用LitePal操作數據庫(記得閱讀最后面的注意事項哦)

一、LitePal簡介 1、(新建項目LitePalTest)正式接觸第一個開源庫---LitePalLitePal是一款開源的Android 數據庫框架,它采用了對象關系映射(ORM)的模式。2、配置LitePal,編輯app/build.gradle文件,在dependencies閉包中…

listview頻繁刷新報錯

在Android編程中使用Adapter時,偶爾會出現如下錯誤:The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI t…

Android 第十三課 SharedPreferences存儲

SharedPreferences是使用鍵值對的方式來存儲數據的。當保存一條數據時,需要給這條數據提供一個對應的鍵,這樣在讀取數據的時候就可以通過這個鍵把相應的值取出來。而且支SharedPreferences還支持多種不同的數據類型存儲,例如:如果…

DSP的Gel作用

轉自:http://blog.csdn.net/azhgul/article/details/6660960最近剛在研究Davinci系,特此MARK下,以資后續學習之用。 DSP的Gel作用 1 GEL文件基本作用 當CCSStudio啟動時,GEL文件加載到PC機的內存中,如果定義了StartUp(…

解決關于登錄校園網顯示不在IP段的問題方案(要看注意事項哦!)

有時,登錄校園網,賬號和密碼都顯示正確,但是卻顯示出“賬號只能在指定IP段登錄”的問題。 那我們就提供了一個解決方案: 使用WinR,并在輸入框,輸入cmd命令:(如下)接著輸入&#xff1…

jquery插件編寫

jQuery為開發插件提拱了兩個方法,分別是: jQuery.fn.extend(object); jQuery.extend(object); jQuery.extend(object); 為擴展jQuery類本身.為類添加新的方法。可以理解為添加靜態方法。是全局的(位于jQuery命名空間內部的函數)…

gtk/Glade編程 編譯命令不成功 解決方法

摘自:http://blog.chinaunix.net/uid-26746982-id-3433656.html 當我們編寫gtk/glade程序,gcc編譯時,用如下命令: #gcc -o server server.c pkg-config --cflags --libs gtk-2.0 報錯:/tmp/ccoXadAd.o: In function …

Android 第十五課 如何使用LitePal從SQLite數據庫中刪除數據(十四課用來保留講解如何向SQLite數據庫中存入數據)

使用LitePal刪除數據的方式主要有兩種,第一種就是直接調用已存對象的delete()方法,所謂已存儲對象就是調用過save()方法的對象,或者說是通過LitePal提供的查詢API查出來的對象,都是可以直接使用delete方法來刪除對象的。這是比較簡…

頁面返回頂部(方法比較)

下面就說下簡單的返回頂部效果的代碼實現&#xff0c;附注釋說明。 1. 最簡單的靜態返回頂部&#xff0c;點擊直接跳轉頁面頂部&#xff0c;常見于固定放置在頁面底部返回頂部功能 方法一&#xff1a;用命名錨點擊返回到頂部預設的id為top的元素 html代碼 <a href"#top…

Android 第十六課 使用LitePal查詢數據

LitePal在查詢API方面做了非常多的優化&#xff0c;基本上可以滿足絕大多數場景的查詢需求&#xff0c;并且代碼也十分整潔。 例如我們需要查詢表中的所有數據&#xff1a; List<books> DataSupport.findAll(Book.class); 沒有冗長的參數列表&#xff0c;只需要調用一下…

linux創建桌面圖標,和開始菜單欄圖標

轉自&#xff1a;http://blog.csdn.net/qq_25773973/article/details/50514767 ###環境&#xff1a;Mint17&#xff0c;&#xff08;其他類似的linux系統是一樣的&#xff09; 如果開始菜單有圖標&#xff0c;創建桌面圖標很簡單&#xff0c;右鍵添加到桌面即可。 如果沒有&am…

ScrollView中使用ListView

轉自 http://blog.csdn.net/fzh0803/article/details/7971391 由于scrollview和listview不能直接共存&#xff0c;在scrollview中直接使用lsitview的話只會顯示一個條目&#xff0c;要使他們共存&#xff0c; 據我所知&#xff0c;有三種方法&#xff1a; 1。如果listview的高度…

Android 第十四課 使用LitePal添加數據(更新數據)

我們注意到當你登錄一個app&#xff0c;是不是需要先注冊呢&#xff1f;&#xff0c;所謂注冊&#xff0c;簡單地來理解是不是就是把輸入框中地數據傳入數據庫中呢&#xff1f; 這里我們設置簡單一點&#xff0c;注冊的信息只包括兩項&#xff0c;一項是用戶名&#xff0c;另一…