我编写了以下程序,要求用户输入上限,并计算和打印每个完美的正方形直至上限。但是,我认为我的is_perfect_square函数效率不高,因为当上限为数千或更高时,计算完美平方需要花费很长时间。我想知道如何提高程序效率,我认为使用带有sqrt的数学模块可以工作,但是我不是数学家,因此需要帮助。
我的程序是:

"""Print all the perfect squares from zero up to a given maximum."""
import math

def read_bound():
   """Reads the upper bound from the standard input (keyboard).
      If the user enters something that is not a positive integer
      the function issues an error message and retries
      repeatedly"""
   upper_bound = None
   while upper_bound is None:
       line = input("Enter the upper bound: ")
       if line.isnumeric() and int(line) >= 0:
           upper_bound = int(line)
           return upper_bound
       else:
           print("You must enter a positive number.")



def is_perfect_square(num):
   """Return true if and only if num is a perfect square"""
   for candidate in range(1, num):
       if candidate * candidate == num:
           return True



def print_squares(upper_bound, squares):
   """Print a given list of all the squares up to a given upper bound"""


   print("The perfect squares up to {} are: ". format(upper_bound))
   for square in squares:
       print(square, end=' ')



def main():
   """Calling the functions"""
   upper_bound = read_bound()
   squares = []
   for num in range(2, upper_bound + 1):
       if is_perfect_square(num):
           squares.append(num)

   print_squares(upper_bound, squares)


main()

最佳答案

您可以使用sqrt

import math
def is_perfect_square(num):
   """Return true if and only if num is a perfect square"""
    root = math.sqrt(num)
    return int(root) - root == 0


或如@PacoH所示:

    return root.is_integer()

关于python - 如何有效枚举所有完美平方?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46442413/

10-11 17:03