I'm trying to create a character frequency dictionary via recursion and it has an empty dicionary as a default parameter. But when I run it consecutively, like defining 2 variables consecutively with the function, it uses a different initial value for the dictionary than an empty one.
def freq_dict(list1, a={}):
if len(list1)>0:
char1= list1[0]
if char1 in a.keys():
a[char1]+=1
n=a.copy()
list1=list1[1:]
return freq_dict(list1, n)
else:
a[char1]=1
n=a.copy()
list1=list1[1:]
return freq_dict(list1, n)
else:
return a
a=freq_dict([1, 2, 2, 1])
b=freq_dict([1, 2, 2, 1])
print(a)
print(b)
This is the code. The expected output would be:
{1: 2, 2: 2}
{1: 2, 2: 2}
But the output I receive is:
I tried printing the dictionary as it was being created and this is the output I got:
The first line is the first time the function is called and it works fine, a starts out empty and reaches the expected value. But in the second line, a begins as {1:1}, which makes no sense because I put the print statement above everything else, it's the first line in the function, yet it uses a={1:!}.