TimeWillTell
TimeWillTell

Reputation: 189

How can I use the combinations object from itertools to find every arrangement of a string that I would input?

My code

from itertools import permutations

original = input('What word would you like to unscramble?: ')

notSoOriginal = permutations(original)

print(notSoOriginal)

Whenever I input a word for the "original" variable, it returns

<itertools.permutations object at 0x02DCC6C0>

What would I change here in order to take the input string for "original" and have it print all the possible rearrangements of the characters? I'm also running Python 3.3 if that makes a difference.

Upvotes: 1

Views: 456

Answers (2)

schesis
schesis

Reputation: 59198

DSM (in the comments) is right that you want permutations rather than combinations.

As to your reported problem - like everything else in the itertools module, permutations and combinations return iterators. So, you can either iterate over the result:

for permuted in permutations(original):
    print(permuted)

... or convert it to a list:

print(list(permutations(original)))

Upvotes: 1

dano
dano

Reputation: 94951

You're looking for:

print([''.join(tup) for tup in permutations(original)])

permutations returns an iterator (not a list) of tuples containing all the permutations of original (e.g. ('t', 'e', 'n'), ('t', 'n', 'e'), ...). So you need to iterate over the iterator, and join each tuple in to a string.

Upvotes: 1

Related Questions