简体   繁体   中英

Is it possible to use itertools.permutations() to print permutations in real time?

I'm writing a simple script that prints all permutations of an input string:

import itertools
inputstring = input("What is your request?")
print("Calculating permutations...")
permlist = (list(itertools.permutations(inputstring)))
for x in range (len(permlist)):
  print ("%s is word #%s"%("".join(permlist[x]),x+1))

But this code must first calculate all permutations, then print them after it is finished. Is there any way to print the output strings in real time instead of at the end of the calculation?

It is the call to list which is consuming all permutations. Instead, just iterate the iterator object which is returned from itertools directly:

perms = itertools.permutations(inputstring)

for i, perm in enumerate(perms, 1):
    word = "".join(perm)
    print("%s is word #%d" % (word, i))

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