我已经写了一个代码来计算多边形的数量,可以从给定的棍子(即:长度)创建。你知道吗
For sticks = [2, 3, 4, 5, 6], the output should be polygonsCount(sticks) = 13.
Here are all the polygons that can be obtained from sticks with lengths 2, 3, 4, 5, and 6:
(2, 3, 4); (3, 4, 5); (2, 4, 5); (2, 5, 6); (3, 4, 6); (3, 5, 6); (4, 5, 6); (2, 3, 4, 5); (2, 3, 4, 6); (2, 3, 5, 6); (2, 4, 5, 6); (3, 4, 5, 6); (2, 3, 4, 5, 6);
该程序运行良好,但由于时间复杂性,它正在跨越更大列表的时间限制。你知道吗
首先,我生成一个给定的棍子列表的幂集。我试图避免[]到所有的[x,x]--2个元素子集,但是失败了,而且,我不认为这会降低时间复杂度。 然后我检查可能的多边形。但我有时间限制。代码如下:
def powersetGenerator(sticks,blankSet):
if sticks ==[]:
yield blankSet
else:
for item in powersetGenerator(sticks[1:],blankSet+[sticks[0]]):
yield item
for item in powersetGenerator(sticks[1:],blankSet):
yield item
def possiblePolygons(array):
sumOfAll = sum(array)
longestSide = max(array)
return longestSide < sumOfAll - longestSide
def polygonsCount(sticks):
powerset = list(powersetGenerator(sticks,[]))
count = 0
for index in range(len(powerset)):
if len(powerset[index])>=3 and possiblePolygons(powerset[index]) == 1:
count=(count+1)%((10**9) + 7)
return count
这基本上是相同的解决方案,具有相同的复杂性,但为了防止重复操作,进行了大量优化。你知道吗
我可能错了,但正确的解决方案的关键可能是计算计数而不构造多边形。数学基础较好的人可能知道答案。你知道吗
另一种方法是使用itertools.组合()从Python标准库生成多边形:
对于没有词典排序的Python3,polygonggenerator()可以重构为:
相关问题 更多 >
编程相关推荐