oguh43
oguh43

Reputation: 85

Permutations of a list

this time im trying to take an sentence input like: Hello World! , split it up via .split(" ") and print all possible combinations, but the code kicks out errors.

x = str(input("Text?"))
x = x.split(" ")
print(x)
ls = []
for i in x:
  ls.append(i)
print(ls)
permutated = permutations(ls,len(ls))
for i in permutated:
  print(permutated)

ls is useless but i tried to use it

Upvotes: 2

Views: 106

Answers (2)

Yaakov Bressler
Yaakov Bressler

Reputation: 12158

When calling the permutations operator, you must use an iterator to instantiate the values.

import itertools

x = "Hello world this is a planet"
x = x.split()

all_combos = list(itertools.permutations(x, r=len(x)))
# print(f'Your data has {len(all_combos)} possible combinations')
# Your data has 720 possible combinations

If you wanted to take this a step further and evaluate for all combinations not-limited to the number of words in your input:

all_combos2 = []
for i in range(1, len(x)+1):
    all_combos2 += list(itertools.permutations(x, i))

print(f'Your data has {len(all_combos2)} possible combinations')
# Your data has 1956 possible combinations

Upvotes: 1

oguh43
oguh43

Reputation: 85

I was printing permutated instead of i :(

Thanks to Perplexabot for their insight in the comments.

Upvotes: 1

Related Questions