Python permutation using backtracking -
i'm trying learn permutation using backtracking. i've written following code stops after first output.
def permutations(str_in, sofar): if len(str_in) != 0: c in str_in: sofar.append(c) temp_str = str_in temp_str.remove(c) print temp_str, sofar permutations(temp_str, sofar) else: print sofar inp = "abcd" str_in = list(inp) permutations(str_in, []) this output i'm getting this:
['b', 'c', 'd'] ['a'] ['c', 'd'] ['a', 'b'] ['d'] ['a', 'b', 'c'] [] ['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd'] i'm sure simple, i'm not able understand mistake i'm making here.
here geeksforgeeks method, bhavya jain, of permuting string. missing logic in code recursive step on sublists , swapping behavior. here visualization.
def permute(a, l, r): if l==r: print tostring(a) else: in xrange(l,r+1): a[l], a[i] = a[i], a[l] permute(a, l+1, r) a[l], a[i] = a[i], a[l] # backtrack # driver program test above function string = "abc" n = len(string) = list(string) permute(a, 0, n-1) output
['a', 'b', 'c'] ['a', 'c', 'b'] ['b', 'a', 'c'] ['b', 'c', 'a'] ['c', 'b', 'a'] ['c', 'a', 'b'] 
Comments
Post a Comment