On Dec 13, 5:18 am, Kirk Strauser <k...@daycos.com> wrote: > At 2008-12-12T18:12:39Z, "Tim Rowe" <digi...@gmail.com> writes: > > > > > Is there a tidy way of making rates and thresholds local to get_rate, > > without recalculating each time? I suppose going object oriented is > > the proper way. > > > #Py3k,UTF-8 > > > rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: > > 0.0173} > > thresholds = list(rates.keys()) > > thresholds.sort() > > thresholds.reverse() > > > def get_rate(balance): > > for threshold in thresholds: > > if balance >= threshold: > > return rates[threshold] > > else: > > return 0.0 > > How 'bout: > > def get_rate(balance): > for threshold, rate in ((100000, .0173), > (50000, .0149), > (25000, .0124), > (10000, .0085), > (0, .006)): > if balance > threshold: > return rate > return .0
(1) you meant "if balance > threshold:" (2) sequential search can be very fast if the sequence is in descending order of probability of occurence ... you might like to consider reversing the order (3) for a much longer table, binary search using a function from the bisect module could be considered (4) in practice, the "default" action would not be "return 0.0"; perhaps something along these lines: if balance < -overdraft_limit: raise Exception(...) return HUGE -- http://mail.python.org/mailman/listinfo/python-list