[英]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.