如何在列表中找到小于n的2的最大幂?

2024-04-26 00:06:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张喜欢的单子

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))]

Tags: ofthetonumber列表forget数字
3条回答

使用一个额外的变量来跟踪要添加的值,并在迭代时构建逻辑。你知道吗

lst = [20, 40, 110]

import math 

def highestPowerof2(n): 
    p = int(math.log(n, 2)) #you do not need semi colons in python
    return int(pow(2, p))

acc = 0 #to keep track of what was the last highest* power
result = []
for n in lst:
    result.append(highestPowerof2(n + acc))
    acc = result[-1]

print(result)
#Output:
[16, 32, 128]

您可以使用以下方法:

lst_power2 = [highestPowerof2(lst[i]+((i>0) and highestPowerof2(lst[i-1]))) for i in range(len(lst))]

而不是

lst_power2 = [highestPowerof2(lst[i]) for i in range(len(lst))]

您可能需要修改您的方法:

  1. 修改你的函数取2个整数。prev_powercurr_num(这是代码中的n
  2. 计算第一个数字的2的幂,并将其添加到结果列表中
  3. 现在将这个数字和列表中的下一个数字传递给highestPowerof2函数

相关问题 更多 >