繁体   English   中英

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

[英]How to make the for loop more efficient in Python

我有一个Python代码,可以产生给定句子的单词的所有可能排列。 而且我希望将这种排列方式写入.txt文档中。 如果我尝试使用9字长的句子来编写代码,那么一切都会很好。 需要一些时间,但是会创建具有所有可能排列的文件。 但是,当我尝试使用一个10个单词长的句子的代码时,它花了很长时间,因为那时的可能排列是10!。 有没有更有效的方法将句子的所有排列保存在txt文件中? 我认为主要问题是我的循环。

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)

答案是否定的 由于存在许多可能的置换,因此这种操作的时间复杂度将始终为N!的数量级。 从数学上来说,渐近地减小该误差是不可能的。

暂无
暂无

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

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