Having some issues with a list after using the itertools permutations function.
from itertools import permutations
def longestWord(letters):
combinations = list(permutations(letters))
for s in combinations:
''.join(s)
print(combinations)
longestWord("aah")
The output looks like this:
[('a', 'a', 'h'), ('a', 'h', 'a'), ('a', 'a', 'h'), ('a', 'h', 'a'),
('h', 'a', 'a'), ('h', 'a', 'a')]
I would like this to be a simple list, but it seems to be coming out as a list of tuples(?). Can anyone help me format this so it comes out as the following:
['aah', 'aha', 'aah', 'aha', 'haa', 'haa']
itertools.permutations(iterable[, r])This tool returns successive length permutations of elements in an iterable. If is not specified or is None , then defaults to the length of the iterable, and all possible full length permutations are generated. Permutations are printed in a lexicographic sorted order.
Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
Permutations of a String using itertools We use the predefined permutations() method in the itertools library to get all the permutations of a given set of objects. To get all the permutations of the word OTP, we need to iterate through it using a for-loop. Each distinct permutation is returned in the form of a tuple.
from itertools import permutations
def longestWord(letters):
return [''.join(i) for i in permutations(letters)]
print(longestWord("aah"))
Result:
['aah', 'aha', 'aah', 'aha', 'haa', 'haa']
A few suggestions:
combination
is not good, as combination is different from permutationPermutations returns an iterator yielding tuples so you need to join them. A map is a nice way to do it instead of your for-loop.
from itertools import permutations
def longestWord(letters):
combinations = list(map("".join, permutations(letters)))
print(combinations)
longestWord("aah")
The way you were doing it, you were joining the letters in each tuple into a single string but you weren't altering the combinations list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With