0

I am trying to run a recursive program that takes an element and iterates over similar elements contained in it but never repeating. I want to keep track of the checked elements with a set type object and I want to repeat the process as many times as I want. This is my code

def assaignPuntuation(song, assigned={"0"}):
 if( song in assigned ):
  return  assigned 
 assigned.add(song)
 def runthrough(songlist, song, assigned):
  for element in songlist:
   assigned = assaignPuntuation (song,assigned=assigned)
  return assigned
 ...
 assigned = runthrough (song, song[4], assigned)
 ...
 return assigned

assaignPuntuation(A)
assaignPuntuation(B)

B is contained in the songlist of A, but when it is not indicated it should not start with all the songs checked in A, but it does.

I expected the set to start with {"0"} every time the function was called with only the song, but it saves the value the first time so I can't repeat it a second time. I tried changing the name of the variables to be different, but it keeps happening and I don't know why.

1 Answers1

0

When you create a function, the function header is executed once at the start of your program. So in your case

def assaignPuntuation(song, assigned={"0"}):

creates a function object with an initialised set for your default argument assigned.

That is why every subsequent call of assaignPuntuation gets the initally initalized assigned set which you mutate inside your function.

To avoid this unexpected mutation follow this approach when dealing with mutable data types:

def assaignPuntuation(song, assigned=None):
    if assigned is None:
        assigned = {"0"}
    # Rest of your function
Wolric
  • 701
  • 1
  • 2
  • 18