简体   繁体   English

Python-计算回文数时长时间停止

[英]Python - long halt while calculating palindrome number

I'm trying to find largest palindromic number made from the product of two 3-digit numbers with my code. 我试图找到由两个3位数字与我的代码的乘积组成的最大回文数。 it works fine for 2-digit and 3-digit, but when I try it with 4-digit numbers, it doesn't work anymore. 它适用于2位和3位数字,但是当我尝试使用4位数字时,它不再起作用。 There is no output or "Process finished with exit code 0" at the end. 最后没有输出或“退出代码为0的过程完成”。 It just halted like it was in an infinite loop. 它就像死循环一样停下来了。

palin = 0
for x in range(1, 10000):
    for y in range(1, 10000):
        mult = x * y

        if str(mult) == str(mult)[::-1]:
            if mult > palin:
                palin = mult

print(palin)

where did I go wrong? 我哪里做错了? I just started Python about a month ago, so my code is still not effective 我大约一个月前才启动Python,所以我的代码仍然无效

Your algorithm is not correct. 您的算法不正确。 The second if should be at the same level as mult = x*y . 第二个if应该与mult = x*y处于同一级别。

I modified your code a little bit. 我修改了一点代码。 With the code below you see that the algorithm does not halt. 在下面的代码中,您会看到算法没有停止。 It's just super slow. 太慢了。 You'll have to wait for minutes. 您将不得不等待几分钟。

pa = 0
for x in range(1, 10000):
    if x % 100 == 0:
        print(x)
    for y in range(x, 10000):
        m = x*y
        if str(m) == str(m)[::-1]:
            if m > pa:
                pa = m
print(pa)

I changed the second range(1, 10000) to range(x, 10000) to eliminate duplicates like 1*2 and 2*1 into a single 1*2. 我将第二个range(1, 10000)更改为range(x, 10000)以将1 * 2和2 * 1之类的重复项消除为单个1 * 2。

If you want a speedup, consider switching to C or C++. 如果要加快速度,请考虑切换到C或C ++。

Also you can reverse the iteration order for an extreme speedup 您也可以颠倒迭代顺序以实现极大的加速

for x in range(10000, 0, -1):
    for y in range(10000, 0, -1):
        m = x*y
        if str(m) == str(m)[::-1]:
            print(m)
            exit(0)

It's kinda an infinite loop, you know, it's very long... 这有点像一个无限循环,这很长...

But actually somehow (maybe my computer is fast :-)) the code ran around 15 seconds only... 但是实际上不知何故(也许我的计算机速度很快:-)),该代码仅运行了15秒左右...

So it's good. 很好

No halt in it, it's just slow. 没有停止,它只是缓慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM