如何减少Python查找球体维度的运行时间



我应该写一段代码,打印不等式x^2+y^2+z^2的整数解的总数<=n、 其中,n是用户输入的整数,介于1和2000之间(包括1和2000(,并将之前所有数量的解相加(例如,n=1返回7,n=2为19,但返回26,依此类推(。这是我的代码:

import math
import itertools
n = int(input("Please enter an integer between 1 and 2000: "))

def sphereCombos(radius):
for i in range(1, radius+1):
count = 0
CombosList = []
rad = int(math.sqrt(i))
range_for_x= range(-rad, rad + 1) 
range_for_y= range(-rad, rad + 1)
range_for_z= range(-rad, rad + 1)
total_perms = list(itertools.product(range_for_x, range_for_y, range_for_z))

for x, y, z in total_perms:
if x*x+ y*y + z*z <= i:
count = count + 1
return count
possible_combos = 0
for i in range(1, n + 1):
possible_combos = possible_combos + sphereCombos(i)
print(possible_combos)

代码完全按照预期工作,但问题是当n设置为2000时,程序花费的时间太长,我需要在2分钟或更短的时间内运行它。我原以为使用.product()会比使用三个嵌套的for循环快得多,但事实并非如此。有什么办法让我减少跑步时间吗?

由于i在全局范围内,所以代码正在工作。注意'sphereCombos(i('将CCD_ 4传递到半径。但该函数实际上在中使用全局irad = int(math.sqrt(i))if x * x + y * y + z * z <= i:

import math
import itertools
n = int(input("Please enter an integer between 1 and 2000: "))

def sphereCombos(radius):
count = 0
rad = int(math.sqrt(radius)) # Changed from i to radius
range_for_x = range(-rad, rad + 1)
range_for_y = range(-rad, rad + 1)
range_for_z = range(-rad, rad + 1)
total_perms = list(
itertools.product(range_for_x, range_for_y, range_for_z))
for x, y, z in total_perms:
if x * x + y * y + z * z <= radius: # Changed from i to radius
count = count + 1
return count

possible_combos = 0
for i in range(1, n + 1):
possible_combos = possible_combos + sphereCombos(i)
print(possible_combos)

最新更新