python-避免for循环中不必要的重复

时间:2019-02-04 05:35:26

标签: python for-loop if-statement

我在理解如何避免for循环中的#redundant重复方面遇到问题。该程序打算打印2到number范围内的数字的除数:

number = int(input('Enter an integer: '))
for divisor in range (2, number):
    if number % divisor == 0:
        print (divisor)
    else:
        print (number, 'has no divisors in the range')

尽管对于您的专业人士来说,它看起来是如此基础,但是我对避免重复感到困惑。

5 个答案:

答案 0 :(得分:0)

在这种方法中,您需要一个附加变量来跟踪是否存在除数。还应删除else块中的缩进。看一下这段代码:

number = int(input('Enter an integer: '))
is_divisor_found = False
for divisor in range(2, number):
    if number % divisor == 0:
        is_divisor_found = True
        print(divisor)
if not is_divisor_found:
    print(number, 'has no divisors in the range')

答案 1 :(得分:0)

保留for filename in * do fileData=$(file "$filename") if [[ "$fileData" == *"PNG image"* ]] then mv "$filename" "0/$filename .png" elif [[ "$fileData" == *"JPEG image"* ]] then mv "$filename" "0/$filename .jpg" elif [[ "$fileData" == *"GIF image"* ]] then mv "$filename" "0/$filename .gif" else echo "error" fi done 作为除数,并在最后检查其是否等于零。

count

答案 2 :(得分:0)

为什么不只做list除数,而仅在除数后才添加。

number = int(input('Enter an integer: '))
divislbes = []

for divisor in range (2,number):
    if number % divisor == 0:
        divislbes.append(divisor)

print((number, "has no divisors in range.") if not divislbes else "The divisbles of ", number, " are: ", divislbes)

输出:

Enter an integer: 5
5 has no divisors in  range.

答案 3 :(得分:0)

我建议保存一个布尔标志,该标志告诉您是否在循环中找到了除数。像这样:

.get()

答案 4 :(得分:0)

range(2, number)的复杂度为O(number)

我们可以将其优化为O(sqrt(number)),如下所示:

import math

number = int(input('Enter an integer: '))
divisor = 2
have_divisor = False

while divisor <= math.sqrt(number):
    if number % divisor == 0:
        print (divisor)
        print (number/divisor)
        have_divisor = True
    divisor += 1

if not have_divisor:
    print (number, 'has no divisors')

参考:https://www.geeksforgeeks.org/find-divisors-natural-number-set-1/