简体   繁体   中英

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.

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. 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.

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):

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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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