0

I'm doing some discrete mathematics stuff for a teacher, he asked me to try and do everything recursively. For some strange reason the list i'm using for a function is the same as it was the last time I called the function. Here's my code:

def extended_euclidean_algorithm(a:int, b:int, equations=list()):
    #This line is just for debugging and checking that my hipothesis was correct
    print (len(equations))
    if b==0:
        return
    if a<b:
        b,a=a,b
    quotient=a//b
    remainder=a%b
    equations.append(f"{a}={quotient}*{b}+{remainder}")
    if extended_euclidean_algorithm(b, remainder, equations):
        return equations
    for i, equation in enumerate(equations):
        equations[i]=equation.split('+')
        equations[i][0]=equations[i][0].split('=')
        equations[i][0]="-".join(equations[i][0])
        equations[i]='='.join(equations[i])
    return True

First time I call it, it's Ok. But second time I call it includes the numbers from the last time I called it.

Y34x4t3
  • 19
  • 7
  • Do you see that you have 3 kinds of returns in your function. One with no arguments, another that returns a list, and another that returns a boolean. Is that what you wanted? I am still researching if thats allowed – Joe Ferndz Aug 23 '20 at 15:59
  • You can send multiple variables in the return. However the prder for the variables have to be intact. You may want to revisit this – Joe Ferndz Aug 23 '20 at 16:05
  • @JoeFerndz It's *allowed* but may not be correct if the caller is not expecting 3 possibilities. – Booboo Aug 23 '20 at 16:05
  • You also want to look at your if statement. You are sending the entire list back for processing. Shouldn't you send only the portion of the list for processing? Look at this example https://stackoverflow.com/questions/30214531/basics-of-recursion-in-python – Joe Ferndz Aug 23 '20 at 16:11

1 Answers1

0

Since you set the list in the arguments, by default the list exists and can be appended to. You better use:

def extended_euclidean_algorithm(a:int, b:int, equations=None):
    equations = equations if equations else []

In this way, equations - if not set - is None rather than an empty list.

Check out the pythontutor visualization here:

gnahum
  • 426
  • 1
  • 5
  • 13
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22