分段错误,需要防止这种情况,并减少我的程序运行时间

2024-04-23 05:33:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我解决了一个问题,我必须找到数字只有4、5和6的总和。。这些数字最多有x 4,最多y 5,最多z 6。我成功地通过了一些样品测试。但是,我无法通过其他测试用例,因为我不断地得到segfault错误。我认为我的程序运行时间很长。如能在减少运行时间、优化解决方案和恢复故障方面提供任何帮助,我们将不胜感激。 下面是我用Python编写的代码:

from itertools import permutations
x , y, z = raw_input().split(' ')
x = int(x)
y = int(y)
z = int(z)
max = ''
for a in range(z):
    max += '6'
for b in range(y):
    max += '5'
for c in range(x):
    max += '4'
perms = [''.join(p) for p in permutations(max)]
chances = []
def substring(string):
    possible = []
    for x in range(len(string) + 1):
        for y in range(x, len(string) + 1):
            possible.append(string[x:y])
    return possible
for d in perms:
    chances += list(set(substring(d)))
chances = list(set(chances))
chances.remove('')
sum = 0
for nstr in chances:
    sum += int(nstr)
print sum 

Tags: inforstringlen时间range数字substring
1条回答
网友
1楼 · 发布于 2024-04-23 05:33:06

知道程序的哪一部分花费的时间最多是有帮助的。在调用排列之后的下半部分,我看到您正在创建潜在的巨大列表(在chances和{}中)。在构建它们之后,您将转换为一个集合(我想是为了消除重复),然后再转换回一个列表。为什么不使用一套呢,像这样:

chances = set()
def substring(string):
    for x in range(len(string) + 1):
        for y in range(x, len(string) + 1):
            chances.add(string[x:y])
for d in perms:
    substring(d)
chances.remove('')
sum = 0
for nstr in chances:
    sum += int(nstr)
print sum 

我不知道这是否能解决你所有的问题,但应该会有帮助。在

相关问题 更多 >