简体   繁体   中英

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

I was printing permutated instead of i :(

Thanks to Perplexabot for their insight in the comments.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM