我正在尝试用最简单的方法解决这个问题,我是初学者,这是我被问到的问题和代码:
程序逻辑替代方案。考虑以下代码,它使用 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/