Skip to main content
 首页 » 编程设计

python之如何在列表中找到小于 n 的 2 的最高幂

2025年05月04日15lvdongjie

我有一个喜欢的列表

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

请您参考如下方法:

您也许可以使用以下内容:

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