Code:
def wordFunc(myDict, currentWord, n):
if n==0: #Base case
print(currentWord)
else:
for char in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
if myDict[char] <= 0 :
continue
elif myDict[char] > 0:
#Decrease current dictionary's character value by 1 then call function
myDict[char] -=1
wordFunc(myDict,currentWord+char,n-1)
#Increase current dictionary's character value by 1
myDict[char] +=1
return
k = input() #Get a string from user input
myDict = {} #Create dictionary calle dmyDict
for char in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
myDict[char] = 0
#Set each letter to a value of 0 for the dictionary
for char in k:
myDict[char] += 1
#Increase each letter value by 1 everytime it occurs in the input
wordFunc(myDict,'',len(k))
#Pass in dictionary, blank string, and length of input's string
Basically the code takes a word as input, and it prints out all combinations of said word.
Since I'm trying to learn recursion on my own, I've just been trying understand this code for hours, but I just can't fully comprehend what's going on.
If anyone could explain to me what I'm missing, I would really appreciate it.
My basic understanding is:
If input is "ABC", then:
Pass in a dictionary containing 'ABC' values(each has a value of 1 in beginning), currentWord as '', and n=3
since A is the first letter of the for loop iterated through and chosen:
Decrease A's dictionary value by 1 to make it 0 and unchoosable
Then combine " + 'A' to equal 'A', pass in n=2 and the dictionary : 'A' = 0, 'B' = 1, 'C' = 1
Next time through, n != 0, so go back to for loop.
B is the next letter:
Decrease B's dictionary value by 1 to make it 0 and unchoosable
Then combine 'A' + 'B' to equal 'AB', pass in n=1 and the dictionary : 'A' = 0, 'B' = 0, 'C' = 1
Next time through, n != 0, so go back to for loop.
C is the next letter:
Decrease C's dictionary value by 1 to make it 0 and unchoosable
Then combine 'AB' + 'C' to equal 'ABC', pass in n=0 and the dictionary : 'A' = 0, 'B' = 0, 'C' = C
Next time through, n == 0, so print the word 'ABC'.
What happens after this point is the part that confuses me.
So currentWord somehow remains at "A", and then as myDict['C'] +=1 finally gets passed in, we get curentWord+C = 'A' + 'C' = 'AC'
Then as myDict['B'] +=1 gets passed in, we get 'AC' + 'B' = 'ACB'
But how does currentWord stay at "A" once you have initially reached "ABC"?
This picture I googled seems to pretty much summarize it perfectly, but I'm still not sure how it works.
I can't wrap my head around it, and it seems like magic to me. Thanks in advance to anyone that has the generosity/patience to explain it to me!
Comment