algorithm - Python while loop never stops even though it should -
i've been going through exercises book on algorithms (with emphasis on python), , strange behavior when try solve problem. exercise straightforward , goal generate random integer k
range(n)
, , locate number through sequence of "yes / no" questions. following code works long n
isn't large, when infinite loop. shouldn't happen because in worst case step_size
equal 1 , position
crawl towards value of k
until position == k
.
when print both step_size
, position
seems position
isn't updating when gets large, i'm guessing has value getting approximated , truncated (this why tried explicitly cast long, may not in fact doing anything). minor parts of code unnecessary, wanted have work general n
. ideas what's going on (you have increase n
behavior i'm talking about)?
from random import randrange math import ceil n = 10**15 k = randrange(n) success = false step_size = ceil(n / 2.0) position = long(ceil(n / 2.0)) print(k) while success == false: if position == k: success = true print(str(int(position)) + ' value of k.') elif k < position: step_size = ceil(step_size / 2.0) position -= step_size print(step_size, position) else: step_size = ceil(step_size / 2.0) position += step_size print(step_size, position)
you need use position += long(step_size)
, position -= long(step_size)
if position == k: success = true print(str((position)) + ' value of k.') elif k < position: step_size = ceil(step_size / 2.0) position -= long(step_size) print(step_size, position,k) else: step_size = ceil(step_size / 2.0) position += long(step_size) print(step_size, position)
if don't position
float not long.
with change n = 10 ** 200
value of:
11008769984569663730780658772914869218303604494435631537943840906720756507580926318660187453313745419228469341648307070867052432521026422402953409000922062458195678772749579263632191432518529106302726 11008769984569663730780658772914869218303604494435631537943840906720756507580926318660187453313745419228469341648307070867052432521026422402953409000922062458195678772749579263632191432518529106302726 value of k.
Comments
Post a Comment