Sugree

Main menu

  • About
    • Self
  • Project
    • Barcode Generator / Reader
    • GT200
    • GeoPin
    • Mitter
    • Red Mob
    • Thairath Breaking News
    • Twitter Android SDK
    • jibjib
    • microblog-purple
    • English
    • Thai

Beauty and the beast

Submitted by sugree on Tue, 07/21/2009 - 00:36
  • Python
  • Thai

@roofimon กับ @Sikachu เรียกร้อง 1, 2 แม้รู้ว่าแพ้แน่ก็ต้องลุย มีติดใจอยู่นิดหน่อย

  • self. นี่ยาวใช้ได้
  • case when งามจนหาอะไรเทียบไม่ได้
  • 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:
  • Beauty and the beast
  • Beauty
  • 10-year history of lottery
  • Simple template in Django
  • MVC in Django
  • Login to post comments
by roofimon (not verified) on Tue, 07/21/2009 - 06:49 #1020

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

  • Login to post comments

Popular Tags

Android BarCamp BarCampBangkok Book Django Drupal Education Family Google Hardware Hardy Health Interview Intrepid Java jibjib Joke Life microblog-purple OpenOffice.org OpenSource Podcast Python Review SoC Social Network Trip Twitter Ubuntu Weekly Suki
more tags

Powered By

debian
apache
drupal
drupal.in.th
openfreehost
inox
feedburner

© 2007-2008 Sugree Phatanapherom. Creative Commons [Feed Content / Comment]
RoopleTheme