Python:有策略地遍历 0-9 的十位数字

标签 python algorithm python-3.x digits

最近,我看了一道数学题,启发了我写一个程序。它要求将数字 0-9 排列一次,以便 xx xxx/xx xxx = 9我写了一个 python 程序来找到解决方案,但遇到了一些麻烦确保数字不同。我找到了一种使用嵌套 whilesifs 的方法,但我对此不太满意。

b,c,x,y,z = 0,0,0,0,0  #I shortened the code from b,c,d,e,v,w,x,y,z
for a in range (10):
    while b < 10:
        if b != a:
            while c < 10:
                if c != b and c != a:
                    while x < 10:
                        if x != c and x != b and x != a:
                            while y < 10:
                                if y != x and y != c and y != b and y != a:
                                    while z < 10:
                                        if z != y and if z != z and y != c and z != b and z != a:
                                            if (a*100 + b*10 + c)/(x*100 + y*10 + z) == 9:
                                                print ()
                                                print (str (a*100 + b*10 + c) + "/" + str (x*100 + y*10 + z)
                                        z += 1
                                    z = 0
                                y += 1
                            y,z = 0,0
                        x += 1
                    x,y,z = 0,0,0
                c += 1
            c,x,y,z = 0,0,0,0
        b += 1
    b,c,x,y,z = 0,0,0,0,0

如您所见,代码非常长且重复,即使是缩短的形式也是如此。在我的笔记本电脑上运行它几乎需要一分钟(而且我的笔记本电脑是新的)。我已经搜索了答案,但我只找到了生成随机数的方法。我也尝试使用 itertools.permutations,但这只显示排列,而不是创建数字。

生成所有十位数字花费的时间太长,我想知道是否有使用 python 3 的更快、更简单且有解释的方法。。 p>

谢谢

最佳答案

采用 Wayne Werner 的解决方案,您可以这样做以添加数字唯一性约束(假设 Python 3):

[(9*num, num) 
 for num in range(10000, 100000 // 9) 
 if len(set(str(num) + str(num * 9))) == 10]

这在我的机器上运行时间为 1.5 毫秒。

请注意,您只能检查 10000 到 100000/9 = 11111 之间的数字。

如果你想允许前面的零,你可以这样做:

[(9*num, num) 
 for num in range(0, 100000 // 9) 
 if len(set(("%05d" % num) + ("%05d" % (num * 9)))) == 10]

这个需要 15 毫秒。

关于Python:有策略地遍历 0-9 的十位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38960714/

相关文章:

Python Flask - WTF SelectField 数据导致错误 _mysql_exceptions.ProgrammingError

python-3.x - 如何修复 : PyInstaller in MSYS2 MinGW 'Your platform is not yet supported'

python - 如何使用 lambda 函数在数据帧上使用 Pandas apply() ?

python - 定位 libmysqlclient_r.so.16 issue

python - 用于 bool 索引的 Pandas、loc 与非 loc

python - 如何通过 http.client.HTTPSConnection 设置 SNI

algorithm - 在随机数据上高效搜索索引的算法或方法有哪些?

python倒数谜题。需要效率方面的帮助

python - 在整个测试套件或 unittest/pytest 中的 at_exit 之后运行命令的 Hook

python - 根据 4 个麦克风的 TDOA 确定 3-D 坐标