algorithm - could any one explain this algo for permutation to me? -


could explain me permutation algo me? know pemutations, can not figure out why works.

s = [1,2,3,4,5,6,7,8,9]   def perm(s, i):     if == len(s):         print s     j in range(i, len(s)):         s[i], s[j] = s[j], s[i]         perm(s, + 1)         s[i], s[j] = s[j], s[i]  //why swaps back?       

this function mutates array s each possible permutation prints permutation , reverses mutation on way out.

at each position i, leaves entries index less i alone, tries later values in position i, , uses recursion find permutations set of fixed values , each choice what's @ position i. @ highest index, there no remaining choices, you've located 1 of permutations, prints result.

i find helpful in understanding sort of recursion put "debug prints" in code @ interesting points start , end of function, , in case @ swaps.

it's not elegant python (some of debug prints should extracted functions), running version of code of these "debug prints" added might instructive.

def perm(s, i):     print '{padding}starting perm({list}, {index})'.format(list=s, index=i, padding=' '*i)     if == len(s):         print s     j in range(i, len(s)):         print '{padding}swapping s[{index1}]={entry1} , s[{index2}]={entry2}'.format(index1=i, entry1=s[i], index2=j, entry2=s[j], padding=' '*i)         s[i], s[j] = s[j], s[i]         perm(s, + 1)         print '{padding}swapping s[{index1}]={entry1} , s[{index2}]={entry2}'.format(index1=i, entry1=s[i], index2=j, entry2=s[j], padding=' '*i)         s[i], s[j] = s[j], s[i]     print '{padding}returning perm({list}, {index})'.format(list=s, index=i, padding=' '*i) 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -