我已经制作了一个程序,允许用户输入最大可能的直角三角形的低音,我的程序将列出三角形所有可能的边的列表。问题是,当我输入诸如10000这样的值时,程序要花费很长时间才能运行。关于如何提高项目的效率,有什么建议吗?
代码:
largest=0
sets=0
hypotenuse=int(input("Please enter the length of the longest side of the triangle"))
for x in range(3,hypotenuse):
for y in range(4, hypotenuse):
for z in range(5,hypotenuse):
if(x<y<z):
if(x**2+y**2==z**2):
commonFactor=False
for w in range(2,x//2):
if (x%w==0 and y%w==0 and z%w==0):
commonFactor=True
break
if not(commonFactor):
print(x,y,z)
if(z>largest):
largest=z
sets+=1
print("Number of sets: %d"%sets)
print("Largest hypotenuse is %d"%largest)谢谢!
发布于 2013-08-14 14:20:53
是像这样吗?
hypothenuse=10000
thesets=[]
for x in xrange(1, hypothenuse):
a=math.sqrt(hypothenuse**2-x**2)
if(int(a)==a):
thesets.append([x,a])
print "amount of sets: ", len(thesets)
for i in range(len(thesets)):
print thesets[i][0],thesets[i][1], math.sqrt(thesets[i][0]**2+ thesets[i][1]**2)编辑:更改,以便您也可以打印集合(此方法在O(n)中,我认为哪种方法是最快的?)注意:如果您想要的集合数量,每一个是两次,例如: 15*2=9*2+12*2 = 12*2+9**2
不确定我是否正确地理解了你的代码,但是如果你让步了12,你是否希望所有可能的三角形都小于12?或者你不想知道写12*2=a*2+b**2的可能性(据我所知)?
如果你想要所有的可能性,我会编辑一些代码。
a*2+b*2 = c**2的所有可能性的,其中c<低值使用(不确定这是否是您想要的东西):
hypothenuse=15
thesets={}
for x in xrange(1,hypothenuse):
for y in xrange(1,hypothenuse):
a=math.sqrt(x**2+y**2)
if(a<hypothenuse and int(a)==a):
if(x<=y):
thesets[(x,y)]=True
else:
thesets[(y,x)]=True
print len(thesets.keys())
print thesets.keys()这在O(n**2)中解决,如果hypothenuse=15,您的解决方案甚至无法工作,您的解决方案提供:
(3,4,5) (5,12,13)组数:2
正确的是:3 (5,12),(3,4),(6,8)
既然5*2+12*2=13*2、3*2+4*2=5*2和6*2+8*2=10**2,而您的方法没有给出第三种选择?编辑:将numpy改为数学,而且我的方法也没有给出倍数,我只是说明了为什么我得到3而不是2,(这3种不同的方法是对问题的不同解决方案,因此所有3种方法都是有效的,所以您的问题解决方案是不完整的?)
发布于 2013-08-14 15:09:55
下面是一个使用预先计算的平方和缓存平方根的快速尝试。可能有许多数学优化。
def find_tri(h_max=10):
squares = set()
sq2root = {}
sq_list = []
for i in xrange(1,h_max+1):
sq = i*i
squares.add(sq)
sq2root[sq] = i
sq_list.append(sq)
#
tris = []
for i,v in enumerate(sq_list):
for x in sq_list[i:]:
if x+v in squares:
tris.append((sq2root[v],sq2root[x],sq2root[v+x]))
return tris演示:
>>> find_tri(20)
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]发布于 2013-08-14 15:50:34
一个非常简单的优化就是任意地确定x <= y。如果(10,15,x)不是一个解决方案,那么(15,10,x)也不会是一个解决方案。这也意味着,如果2x**2 > hypoteneuse**2,那么您可以终止算法,因为没有解决方案。
https://stackoverflow.com/questions/18234207
复制相似问题