我有一张喜欢的单子
lst=[20,40,110]
我想在列表中找到2的最高幂
For the first number, the highest power of 2 will get the first element of the list as input. So the result is 16 (closest to 20)
For the next numbers, it will get the summation of previous result (i.e 16) and current number (.i.e 40) so the closest number will be 32 (closest 40 +16)
所以我期望的结果是
lst_pow2=[16,32,128]
这是我目前的代码来寻找一个数字的最高数字,但对于我的问题,它应该改变一些东西,因为我的输入是列表。有什么建议吗?谢谢
# Python3 program to find highest
# power of 2 smaller than or
# equal to n.
import math
def highestPowerof2(n):
p = int(math.log(n, 2));
return int(pow(2, p));
所以我试过了,但它不能做总和
lst_power2 = [highestPowerof2(lst[i]) for i in range(len(lst))]
使用一个额外的变量来跟踪要添加的值,并在迭代时构建逻辑。你知道吗
您可以使用以下方法:
而不是
您可能需要修改您的方法:
prev_power
和curr_num
(这是代码中的n
)highestPowerof2
函数相关问题 更多 >
编程相关推荐