我解決了一個難題,但需要優化我的解決方案。難題說我要取一個字符串S,查找其字符的所有排列,對結果進行排序,然後返回該列表中出現的其中一個基於索引的索引號S。優化一種查找字符串的所有排列的方法
例如,字符串'bac'出現在其排列列表中的第3個位置:['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
。
我的問題是,謎題限制我的執行時間爲500毫秒。其中一個測試用例通過「BOOKKEEPER」作爲輸入,需要4.2秒才能完成。
我採用了一種(可能是天真的)動態編程方法,使用memoization,使用一個由特定字符集的特定排列組成的字典,但這還不夠。
我的瓶頸是什麼?
我正在分析,看看我能否回答我自己的問題,但我邀請那些直接看到問題的人幫助我理解我是如何減緩這種情況的。
編輯:我的解決方案似乎超過itertools.permutations
。 10秒以上輸入「問題」。但公平地說,這包括時間打印,所以這可能不是一個公平的比較。即便如此,我寧願提交具有競爭力表現的手寫解決方案,以瞭解爲什麼我的選擇不如選擇模塊。
memo = {}
def hash(word):
return ''.join(sorted(word))
def memoize(word, perms):
memo[hash(word)] = perms
return perms
def permutations(word, prefix = None):
"""Return list of all possible permutatons of given characters"""
H = hash(word)
if H in memo:
return [s if prefix is None else prefix + s for s in memo[H]]
L = len(word)
if L == 1:
return [word] if prefix is None else [prefix + word]
elif L == 2:
a = word[0] + word[1]
b = word[1] + word[0]
memoize(word, [a, b])
if prefix is not None:
a = prefix + a
b = prefix + b
return [a, b]
perms = []
for i in range(len(word)):
perms = perms + permutations(word[:i] + word[i+1:], word[i])
memoize(word, perms)
return [prefix + s for s in perms] if prefix is not None else perms
def listPosition(word):
"""Return the anagram list position of the word"""
return sorted(list(set(permutations(word)))).index(word) + 1
print listPosition('AANZ')
'itertools.permutations'如何執行?請參閱'timeit'模塊或IPython魔術'%timeit' –
@WayneWerner哦,忘記提及了。更糟的是。 10s +用於輸入「問題」 –
@WayneWerner請參閱編輯 –