简体   繁体   English

为什么我的python程序不能永远运行? “意外退出”

[英]Why doesn't my python program run forever? “Unexpectedly quit”

I am doing a math problem that requires me to multiply numbers and check to see if they are palindromes. 我正在做一个数学问题,要求我将数字相乘并检查它们是否是回文。

import sys
sys.setrecursionlimit(1000000)
import time

def values():
    x=999
    y=999
    product=0
    generator(x,y,product)

def generator(x,y,product):
    while x >= 900:
        product=x*y
        strp=str(product)
        check=strp[::-1]
        print (check)
        time.sleep(0.1)
        if strp==check:
            print ("done")
        x=x-1
    else:
        y=y-1
        generator(x,y,product)

values()

I am using Mac, and it goes through the loop a couple of times but then displays a "Pytho quit unexpectedly" error. 我使用的是Mac,它经过几次循环,但是显示“ Pytho意外退出”错误。

Your program is crashing because your recursion loop doesn't stop. 您的程序崩溃,因为递归循环没有停止。 When x reaches the value of 900 the generate function always calls the else branch of its code. x达到900的值时, generate函数将始终调用其代码的else分支。 You reed to add a condition for the loop to stop. 您需要为循环停止添加条件。 Otherwise it fills up the memory, making the program crash because recursion loops have a limit on how many times you call them. 否则,它将填满内存,使程序崩溃,因为递归循环对您调用它们的次数有限制。

As per the answer above, your recursion never stops because once x = 900 it always recurses by calling the else code. 按照上面的答案,递归永远不会停止,因为一旦x = 900,它总是通过调用else代码来递归。

I suggest the following solutions: a) If you're interested in keeping y at 999 until x is 900 and then decrease y until it's 900 you should add the following to your else (ie do 999x999, 999x998... 999x900 ... 998x900 ... 900 x 900): 我建议以下解决方案:a)如果您有兴趣将y保持在999直到x为900,然后将y减小到900,则应在其他项中添加以下内容(即999x999、999x998 ... 999x900 ... 998x900 ... 900 x 900):

else:
    if y >= 900:
       generator(x,y,product)
       y=y-1

b)If you want to recurse on both of them (ie decrease them in parallel): b)如果您要递归使用它们(即同时减小它们):

def generator(x,y,product):
    if x >= 900 and y >=900:
        product=x*y
        strp=str(product)
        check=strp[::-1]
        print (check)
        time.sleep(0.1)
        if strp==check:
            print ("done")
        x=x-1
        y=y-1
        generator(x, y, product)

Personally I would recommend the second solution as it's neater. 我个人建议第二种解决方案,因为它更整洁。

Please note that when recursing on both of them you don't need to have while loops, an if check is enough. 请注意,当对它们两者进行递归操作时,都不需要while循环,而if检查就足够了。

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

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