在Python 3.x中将for循环转换为while循环

时间:2019-05-05 06:21:53

标签: python python-3.x

我使用“ for循环”编写的程序是正确的,并且通过了所有测试用例,但是,当我将“ for循环”转换为“ while循环”时,发生了“ IndexError”,我想知道我的问题是什么程序使用“ while循环”。

nums = []
remainders=[]
while True:
    num=int(input('Number: '))
    if num==0:        
        break
    nums.append(num)    
if len(nums)==0:
    print('No integers were entered')
    exit()
a=0
while a<len(nums):
    num=nums[a]
    remainder=num%10
    remainders.append(remainder)
    a+=1
index=remainders.index(max(remainders))
count=0   
for i in remainders:
    if i > remainder:
        remainder=i
        count=0
    if i ==remainder:
        count+=1
if count ==1:
    print('The most interesting integer was: {}'.format(nums[index]))  
elif count>1 and count<len(nums):
    print('Two or more integers are the most interesting')
else:
    print('All integers have the same remainder')  

那是我使用for循环编写的程序,这个答案是正确的

nums = []
remainders=[]
while True:
    num=int(input('Number: '))
    if num==0:        
        break
    nums.append(num)    
if len(nums)==0:
    print('No integers were entered')
    exit()
a=0
while a<len(nums):
    num=nums[a]
    remainder=num%10
    remainders.append(remainder)
    a+=1
index=remainders.index(max(remainders))
count=0   
k=0
while k<len(remainders):
    remainder=remainders[k]
    if remainders[k]>remainder:
        remainder=remainders[k]
        count=0
    k+=1    
    if remainders[k]==remainder:
        count+=1
    k+=1    
if count ==1:
    print('The most interesting integer was: {}'.format(nums[index]))  
elif count>1 and count<len(nums):
    print('Two or more integers are the most interesting')
else:
    print('All integers have the same remainder')  

此答案不正确,因为第二个while循环存在一些问题

actual:
Number: 4
Number: 20
Number: 9
Number: 3
Number: 5
Number: 0
Traceback (most recent call last):
  File "numbers.py", line 26, in <module>
    if remainders[k]==remainder:
IndexError: list index out of range
expected:
Number: 4
Number: 20
Number: 9
Number: 3
Number: 5
Number: 0
The most interesting integer was: 9

1 个答案:

答案 0 :(得分:1)

您的代码中有两个问题

  • 您执行两次k+=1,这会导致list index out of range错误,请执行一次

  • 当您执行remainder=remainders[k] if remainders[k]>remainder时,该结果始终为False,请删除行remainder=remainders[k]

记住这一点,以下while循环应该起作用

while k<len(remainders):
    if remainders[k]>remainder:
        remainder=remainders[k]
        count=0
    if remainder==remainders[k]:
        count+=1
    #Increment only once
    k+=1