[英]List comprehension to return the sum of n/2…?
Basically, how do I write the same function in list comprehension? 基本上,我该如何在列表理解中编写相同的函数?
def blah(n):
if n <= 1:
return 1
return n + blah(n/2)
print blah(32)
I don't really need this for anything other than proving to myself that custom step for any range in list comprehension is actually possible. 除了向自己证明列表理解中任何范围的自定义步骤实际上是可能的之外,我实际上并不需要此。
import math
def lcsum(n):
return sum([n>>i for i in range(int(math.log(n, 2))+1)])
You'd need to generate the sequence of halved numbers: 您需要生成减半数的序列:
def halved(n):
while n:
yield n
n >>= 1
Then use turn that into a list: 然后使用将其转换为列表:
list(halved(32))
or just directly sum it: 或直接将其求和:
sum(halved(32))
You'd have to use math.log()
to turn that into a range()
-suitable value: 您必须使用math.log()
将其转换为range()
-合适的值:
import math
sum(n >> i for i in range(int(math.log(n, 2)) + 1))
I would write it like this, if you really wanted some kind of list comprehension in there: 如果您真的想在其中进行列表理解,我会这样写:
import math
def sumOfNHalf( n ):
return sum( [ 2**x for x in range( 0, int( math.log( n, 2 ) + 1 ) ) ] )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.