Anonymous user
Price fraction: Difference between revisions
→{{header|Python}}: Bisection library code shown
m (→{{header|C#}}: Fix C# HTTP bug) |
(→{{header|Python}}: Bisection library code shown) |
||
Line 480:
return _cout[ bisect.bisect_right(_cin, centsin) ]</lang>
Other options are to use the fractions or decimals modules for calculating money to a known precision.
<br>'''Bisection library code'''<br>
:The <code>bisect</code> Python standard library function uses the following code that improves on a simple linear scan through a sorted list:
:<lang python>def bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]: hi = mid
else: lo = mid+1
return lo</lang>
=={{header|Ruby}}==
|