Mark Norman
Mark Norman

Reputation: 11

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.

Upvotes: 0

Views: 146

Answers (2)

ShadowMitia
ShadowMitia

Reputation: 2533

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.

Upvotes: 1

Andrei-Marius Longhin
Andrei-Marius Longhin

Reputation: 563

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 (i.e. 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 (i.e. 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.

Upvotes: 0

Related Questions