2012-03-28 137 views
2

我正在努力工作,这一点是最简单的方法,我是初学者,这是一个问题我一直在问及代码:这个while循环转换为更有效,同时循环

程序逻辑的替代品。考虑下面的代码,它使用一个while循环,并找到标志来搜索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') 

就问我要不要的问题是一对夫妇,但第一个是困惑我,

一)首先,重写while循环else子句的代码,以消除所发现的标志,并最终如果声明。

任何帮助表示赞赏。谢谢。

+1

是这个家庭作业? – jamylak 2012-03-28 11:03:19

+0

#1重写没有'found'变量的代码。 #2重写代码,这样唯一的if语句在while循环中(这必须作为#1的结果完成)......你允许使用函数吗? – 2012-03-28 11:05:00

+2

这个问题不属于http://codereview.stackexchange.com吗? – EOL 2012-03-28 11:08:13

回答

1
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') 
+0

谢谢,这正是我正在寻找唯一的事情是否将计数作为一个else子句? – thechrishaddad 2012-03-28 11:22:44

+0

合并while语句的else子句,将最后一行代码更改为'else:print(X,'not found')' – codetantra 2012-03-28 12:41:03

1

Python带有batteries

使用index方法:

L = [...] 
try: 
    i = L.index(2**X) 
    print("idex: %d"%i) 
except ValueError as err: 
    print("not found") 
+0

这是做手头工作的方式,但这似乎不是对这个问题的回答(“首先,使用其他while循环子句,...”) – EOL 2012-03-28 11:09:09