简体   繁体   中英

How to make the for loop more efficient in Python

I have a Python Code that produces all possible permutations of the words of a given sentence. And I want this permutations to be written in a .txt-document. If I try the code with a 9-word-long sentence, everything works fine. It takes a while but the file with all the possible permutations is created. But when I try the code with a 10-word-long sentence, it takes much to long because the possible permutations then are 10!. Is there a more efficient way to save all the permutations of a sentence in txt-file? I think the main problem is my for-loop.

parser = optparse.OptionParser(usage=help_text)
parser.add_option("-f", "--file", dest="filename",
                  help="write the permutations to FILE", metavar="FILE")
(options, args) = parser.parse_args()

# read the input
sentence = input("Sentence: ")
sent_list = re.split(r"[\s.,!?:\"\';()]+", sentence)
# remove empty strings from the sent_list
sent_list = [s for s in sent_list if s is not ""]

result = ""
perm_iterator = itertools.permutations(list(sent_list),r=None)


for item in perm_iterator:
    print("item in perm_iterator",item)
    result += "".join(item);



# print to file if file option is not None
if options.filename is not None:
    with open(options.filename, 'w') as f:
        f.write(result)
    print("The different variants of the sentence got saved in {} .".format(options.filename))
else:
    print(result)

The answer is no . The time complexity of such an operation will always be of the order of N!, since there are that many possilbe permutations. Reducing this asymptotically is mathematically impossible.

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