2010-07-13

Python Lost $20 Quiz

You can get $999 on the first day, and get a half of it (floored, that is $499) on the second day, and get half ... eventually how much you get in total? You received an e-mail, the payment in each days are printed in it, comma-separated. You split it with comma, eval and sum. Your answer is $1970. Oh, really is it correct?



>>> def format(xs):
return ",".join("%03d" % x for x in xs)

>>> format([123, 456, 789])
'123,456,789'



>>> def list_gen(n):
while n:
yield n
n /= 2

>>> list(list_gen(64))
[64, 32, 16, 8, 4, 2, 1]



>>> email = format(list_gen(999))
>>> sum(eval(s) for s in email.split(","))
1970



>>> total = 0
>>> 999
999
>>> total += _
>>> _ / 2
499
>>> total += _
>>> _ / 2
249
>>> total += _
>>> _ / 2
124
>>> total += _
>>> _ / 2
62
>>> total += _
>>> _ / 2
31
>>> total += _
>>> _ / 2
15
>>> total += _
>>> _ / 2
7
>>> total += _
>>> _ / 2
3
>>> total += _
>>> _ / 2
1
>>> total += _
>>> _ / 2
0
>>> total
1990

No comments: