python - 将此 while 循环转换为更高效的 while 循环

标签 python python-3.x

我正在尝试用最简单的方法解决这个问题,我是初学者,这是我被问到的问题和代码:

程序逻辑替代方案。考虑以下代码,它使用 while 循环和 find 标志在 2 的幂列表中搜索 2 的五次幂 (32) 的值。它存储在名为 power.py 的模块文件中。

L = [1, 2, 4, 8, 16, 32, 64]
X = 5
found = False
i = 0

while not found and i < len(L):
    `if 2 ** X == L[i]:`
        found = True
    else:
        i = i+1

if found:
    ('at index', i)
else:
     print(X,'not found')

它要求我做的问题是几个,但第一个让我感到困惑,

a.)首先,使用 while 循环 else 子句重写代码,以消除找到的标志和最终的 if 语句。

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

L = [1, 2, 4, 8, 16, 32, 64] 
X = 5 
i = 0 
while i < len(L): 
    if 2 ** X == L[i]: 
        print('at index',i)
        break;
    i = i+1 
    if i==len(L): print(X,'not found') 

关于python - 将此 while 循环转换为更高效的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9906112/

相关文章:

python - Tensorflow GPU安装Ubuntu 16.04错误(libcuda.so未找到)

python - 对于 MultinomialNB,Sklearn 偏向正值

python-3.x - Django forms.ModelForm slugfield db_index=True

python - 可变距离的高效 NumPy 行旋转

python - 导入 CSV 文件时 Python 3 中的 UnicodeDecodeError

python - PyQt5 Painter 组对象

python - 如何通过 OLS 回归输出摘要检测 python 中的特定警告

python - 如何将python Unicode字符串转换为字节

python - 所有这些 OpenCV Python 接口(interface)之间有什么不同?

python - numpy 在进行矩阵乘法时是否使用内存中的空间局部性?