python - List comprehension to return the sum of n/2...? -
basically, how write same function in list comprehension?
def blah(n): if n <= 1: return 1 return n + blah(n/2) print blah(32) i don't need other proving myself custom step range in list comprehension possible.
you'd need generate sequence of halved numbers:
def halved(n): while n: yield n n >>= 1 then use turn list:
list(halved(32)) or directly sum it:
sum(halved(32)) you'd have use math.log() turn range()-suitable value:
import math sum(n >> in range(int(math.log(n, 2)) + 1))
Comments
Post a Comment