第一次写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.mzph.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;另一…