简体   繁体   English

如何在Python中提高for循环的效率

[英]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. 我有一个Python代码,可以产生给定句子的单词的所有可能排列。 And I want this permutations to be written in a .txt-document. 而且我希望将这种排列方式写入.txt文档中。 If I try the code with a 9-word-long sentence, everything works fine. 如果我尝试使用9字长的句子来编写代码,那么一切都会很好。 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!. 但是,当我尝试使用一个10个单词长的句子的代码时,它花了很长时间,因为那时的可能排列是10!。 Is there a more efficient way to save all the permutations of a sentence in txt-file? 有没有更有效的方法将句子的所有排列保存在txt文件中? 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. 由于存在许多可能的置换,因此这种操作的时间复杂度将始终为N!的数量级。 Reducing this asymptotically is mathematically impossible. 从数学上来说,渐近地减小该误差是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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