Permutations using a Combinations Generator (Python)

vegaseat 1 Tallied Votes 429 Views Share

Because of their demand only nature, generators are ideal for finding the combinations of larger sequences. This code applies a Python generator to find the combinations of the sequence. Since permutations are a special case of combinations for all the items in a sequence, I have expanded the result to give the permutations of a string.

# using a combinations-generator for larger permutations
# tested with Python24 by      vegaseat       10sep2006

def xcombinations(items, n):
    if n == 0:
        yield []
    else:
        for i in xrange(len(items)):
            for cc in xcombinations(items[:i] + items[i+1:], n-1):
                yield [items[i]] + cc

def xpermutations(items):
    """permutations are just a special case of combinations"""
    return xcombinations(items, len(items))

# test the above functions ...
if __name__=="__main__":
    word = 'workmen'
    charList = list(word)  # ['w', 'o', 'r', 'k', 'm', 'e', 'n']
    print "Permutations of '%s' -->" % word
    for pm in xpermutations(charList):
        # reform the word
        print ''.join(pm)

"""
Permutations of 'workmen' -->
workmen
workmne
workemn
workenm
worknme
worknem
wormken
wormkne
wormekn
wormenk
wormnke
...

"""
Stefan_3 0 Newbie Poster

import itertools
s='workmen'
print ["".join(map(str,x)) for x in itertools.permutations(list(s),len(s))]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.