Pages

Search This Blog

November 27, 2012

permutations of string in lexicographic order

# compute the permutations of a string in
# increasing order (lexicographic order)
# Eg: for string ABC, output should be ABC, ACB, BAC, BCA, CAB,CBA
s = "DAECB"
t = list(s)
t.sort()
def permute(soFar, remaining):
    """
    recursive algorithm to permute astring
    """
##
##    print 'soFar ', soFar, ' remaining ', remaining
    if len(remaining) == 0:
        printstr(soFar)
        return
    for x in xrange(len(remaining)):
        p = soFar+list(remaining[x])
        if x ==0:
            q=remaining[x+1:]
        else:
            q=remaining[0:x]+remaining[x+1:]
            
##        print p, ' ', q
        
        permute(p, q)
        
x=[]
permute(x,t)

No comments:

Post a Comment