Problems understanding working recursive combinations code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ascender
    New Member
    • Oct 2012
    • 3

    Problems understanding working recursive combinations code

    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
    The code already works, but I'm not the one who wrote it.
    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!
    Attached Files
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    It sounds like you believe that current word references the same object each time the function is called. That is not the case. In your example, the lowest function, the one where n = 0, that one sees current word as abc. But once you exit out of that function and return to the higher level function, that version of current word, the one that's equal to abc, no longer exists, that higher level function only sees its version of current word which is equal to ab.

    Comment

    • Ascender
      New Member
      • Oct 2012
      • 3

      #3
      Ok thanks, I think I am getting somewhere, but what exactly happens after the function exits and the string ABC is made?
      At first I thought after the function exits:
      It rolls back to the pause state of AB from the last recursive call, and C is increased to 1.
      Then it rolls back to the second last recursive call with A, and B isn't available since it was incremented after this recursive call. But C is now 1 since the incrementation finally got counted, so it adds AC.
      Then with AC, it runs through the function again and chooses B since B's incrementation finally took effect.
      So then the second permutation is ACB

      But then I looked at the values, and it seems that both c and b are 1 when it chooses AC instead of AB, so I am still not really understanding why it returns ACB instead of ABC again.

      Any hints??

      Thanks!

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        You're almost there. They are both one. But in the previous iteration, it already checked b so it's not going to check it again, so it moves on to check c. So it recurses with a=0, b=1, c=0, and new word='ac'. In the new instance of the function, it starts checking from a again and finds b. Giving you acb. But when it returns to the prior call, it's not going to start the check over again from a, it continues from whichever letter it left off at.

        Comment

        • Ascender
          New Member
          • Oct 2012
          • 3

          #5
          My mind is blown. Thank you sir~ I think I understand it now :)

          Comment

          Working...