我怎样才能加快我的python程序

时间:2016-03-24 19:33:39

标签: python optimization teaser

以下是我的剧本:

from math import trunc

def solver(number,number2, numberofdigits):
    seq = str(number),str(number2), str(number - number2)
    digits = "".join(seq)
    goodChecks = 0
    count= numberofdigits/3
    for i in range(1,10):
        if digits.count(str(i)) == count:
            goodChecks += 1
    if goodChecks == 9:
        return digits
    else:
        return False


middlenumberdic = {}
middlenumber =[]
successes = 0
num_of_digits = int(input("please enter a number of digits, which is a multiple of 3"))
if num_of_digits == 3:
    minY = 381
    maxY = 987
if num_of_digits == 6:
    minY =246912
    maxY = 998877

if num_of_digits == 3:
    minX = 123
if num_of_digits == 6:
    minX =123123


for y in range(minY, maxY+1):
    numberlist = []
    if y%100 == 0:
        print(y)
    for x in range(minX,trunc(y/2)):
        digits = solver(y,x,num_of_digits)
        if digits is not False:
            successes += 2
            print(digits)
            numberlist.extend([x,y-x])
            middlenumber.extend([x, y-x])

print("")
print("I found: ", successes, " successful solution to your brainteaser")
if successes < 20:
    print("there were almost no solutions")
elif successes < 100:
    print("there were not many solutions")
elif successes < 1000:
    print("there were more than a hundred solutions it is definitely not impossible :)")
else:
    print("that's a lot of successes")

print("All the ", successes, " succesful solutions i am now going to show you :)")
print("There were ", len(middlenumber) - len(set(middlenumber)) , " duplicates, by the way :)")

items = sorted(middlenumberdic.items())
for key, value in items :
    if not not value:
        print(key, " : ", ", ".join( repr(e) for e in value ))

所以我创造了一个脑力激荡器,我称之为“不可能的问题”。在这个脑力激荡器中,目的是创建一个有效的3位数减法,使用1到9之间的每个数字 以下是其中一个解决方案的示例:873-254 = 619这是有效的,因为每个数字都使用一次。

有关详细信息,请观看我制作的视频:https://www.youtube.com/watch?v=-2i1nOy6mfo&ab_channel=EpicVideos

在发现难以得出答案后,我创建了这个程序。它基本上做的是遍历每个可能的3位数减法,如果找到符合标准的减法,则打印它。

我的程序工作得很好,但后来我决定你能为6位数做同样的事吗?对于3位数问题,程序有9 ^ 6个可能性进行迭代。这是一个微不足道的531,441次迭代。然而,对于6位数,存在9 ^ 12个可能性,这是一个重复的282,429,536,481次迭代。这将耗费我的计算机时间来解决。

我已经尝试过优化我的程序,但我无法弄清楚如何更快地完成它。所以,如果你发现在任何时候都有一种方法可以优化它,请你告诉我。三江源

0 个答案:

没有答案
相关问题