patternpythonMinor
Find the highest number satisfying a condition in an infinite range
Viewed 0 times
findnumbertheconditioninfinitesatisfyingrangehighest
Problem
I wrote the below function for doing a variation of bisection search that I came up with. This can be useful when the higher bound is not known. It assumes that as number increases the result of the condition is also increasing.
For example - find the largest classroom size where the probability of two students sharing the same birthday is less than 0.99.
If I have a function that finds the probability of two students sharing the same birthday based on number of classrooms then I can pass that function and perform a bisection search over an infinite range to find the highest number.
I wanted to know whether this can be written in a better way - according to either algorithm or Python.
For example - find the largest classroom size where the probability of two students sharing the same birthday is less than 0.99.
If I have a function that finds the probability of two students sharing the same birthday based on number of classrooms then I can pass that function and perform a bisection search over an infinite range to find the highest number.
def largest_satisfying_condition(condition):
lo, hi = 1, 3
mid = None
lowest_hi_false = float('inf')
while lo != hi:
mid = (lo + hi) / 2
if condition(mid):
lo, hi = mid, hi * 2
if hi > lowest_hi_false:
#Because any value greater than this will give false result
hi = lowest_hi_false - 1
else:
lo, hi = lo, mid
if hi < lowest_hi_false:
#No need to go over this when increasing hi
lowest_hi_false = hi
return midI wanted to know whether this can be written in a better way - according to either algorithm or Python.
Solution
if/else inside the loop doesn't look clean. Consider splitting the code into two parts:# Find the "good" range
while condition(hi):
lo, hi = hi, hi * 2
# At this point it is known that condition(lo) is True,
# and condition(hi) is False. A normal bisection search
# follows.
return binary_search(lo, hi, condition)It would be also worthy to factor the setup loop out in its own function.
Code Snippets
# Find the "good" range
while condition(hi):
lo, hi = hi, hi * 2
# At this point it is known that condition(lo) is True,
# and condition(hi) is False. A normal bisection search
# follows.
return binary_search(lo, hi, condition)Context
StackExchange Code Review Q#84510, answer score: 6
Revisions (0)
No revisions yet.