Beauty and the beast
@roofimon กับ @Sikachu เรียกร้อง 1, 2 แม้รู้ว่าแพ้แน่ก็ต้องลุย มีติดใจอยู่นิดหน่อย
self.นี่ยาวใช้ได้casewhenงามจนหาอะไรเทียบไม่ได้- built-in regular expression มันง่ายแบบนี้นี่เอง Perl ชัดๆ
เมื่อเขียนตรงๆ สู้ไม่ได้ก็ต้องแอบแก้ตรรกะ แพ้อยู่ดี... มันเป็นชะตากรรม
import re import math class RateStrategyParser: COMMAND = re.compile(r'^minimum\s+(\d+)\s+(\w+)\s*,\s*'+ r'nextcharge\s+(\d+)\s+(\w+)\s*'+ r'(:\s*(\d+)\s*%)?$', re.I) def __init__(self, str): m = self.COMMAND.match(str) if m: match = m.groups() self.minimum = self._convert_time(match[0], match[1]) self.nextcharge = self._convert_time(match[2], match[3]) if match[4]: self.nextcharge_rate = float(match[5])/100.0 else: self.nextcharge_rate = 1.0 else: raise Exception("Unable to parse input: %s" % str) def calculate(self, price, time): total = 0 if time > self.minimum: time -= float(self.minimum) total = price+math.ceil(time/self.nextcharge)*self.nextcharge_rate*price return total def _convert_time(self, time, unit): for exp, factor in [(r's|sec|seconds?', 1), (r'm|min|minutes?', 60), (r'h|hours?', 3600)]: if re.match(exp, unit): return int(time)*factor raise Exception("Unknown Unit: %s %s" % (time, unit)) if __name__ == '__main__': rp = RateStrategyParser("minimum 1 min, nextcharge 6 sec : 10%") print "%.2f" % rp.calculate(24.0, 72)
Roti (alpha) thinks you may like these:
- Login to post comments







ชาบู ชาบู คนที่ทำสำเร็จได้คือยอดคน