如何在Python中使for循环更有效

时间:2018-04-20 14:22:01

标签: python performance for-loop permutation itertools

我有一个Python代码,可以生成给定句子的所有可能的排列。我希望这些排列可以用.txt文档编写。 如果我用9个字长的句子尝试代码,一切正常。这需要一段时间,但会创建具有所有可能排列的文件。但是当我尝试使用长度为10个字的句子时,需要很长时间,因为可能的排列是10!有没有更有效的方法来保存txt文件中句子的所有排列?我认为主要问题是我的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)

1 个答案:

答案 0 :(得分:1)

答案是。这种操作的时间复杂度总是大约为N!,因为存在许多可能的排列。渐近地减少这种情况在数学上是不可能的。

相关问题