interesting exercise
Christopher Cormie
ccormie at aussiemail.com.au
Tue May 8 02:28:04 EDT 2007
Michael Tobis wrote:
> I want a list of all ordered permutations of a given length of a set
> of tokens. Each token is a single character, and for convenience, they
> are passed as a string in ascending ASCII order.
>
> For example
>
> permute("abc",2)
>
> should return ["aa","ab","ac","ba","bb","bc","ca","cb","cc"]
If N is constant and small (e.g hard-coded N of 2), list comprehensions
provide a concise solution:
a = "abc"
b = [(x,y) for x in a for y in a]
c = ["".join(z) for z in b]
print b
print c
Gives:
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', ' a'), ('c',
'b'), ('c', 'c')]
['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
Cheers,
Chris
More information about the Python-list
mailing list