我的問題很簡單。
我有這個代碼
def get_neighbors(word, choices):
return set(x for x in choices if x[0] == word[-1])
def longest_path_from(word, choices):
choices = choices - {word}
neighbors = get_neighbors(word, choices)
if neighbors:
paths = (longest_path_from(w, choices) for w in neighbors)
max_path = max(paths, key=len)
else:
max_path = []
return [word] max_path
def longest_path(choices):
return max((longest_path_from(w, choices) for w in choices), key=len)
從一組單詞中找出第一個單詞的最后一個字母等于第二個單詞的第一個字母的最長序列
我想調整此代碼以找到最長的回圈序列。
所以舉個例子。
- long_path({'ca', 'abc', 'cd', 'da'}) 回傳 ['ca', 'abc', 'cd', 'da'] 這是正確的,但我希望它是 [" abc","cd","da"] 所以還有一個條件,那就是最后一個單詞的最后一個字符匹配第一個單詞的第一個字符。
我似乎找不到把它放在哪里。
感謝您的幫助。
uj5u.com熱心網友回復:
根據我的評論,longest_path_from將找到的所有序列回傳給您。只需遍歷那些并丟棄那些不是圓形的。
def get_neighbors(word, choices):
return set(x for x in choices if x[0] == word[-1])
def longest_path_from(word, choices):
choices = choices - {word}
neighbors = get_neighbors(word, choices)
if neighbors:
paths = (longest_path_from(w, choices) for w in neighbors)
max_path = max(paths, key=len)
else:
max_path = []
return [word] max_path
def longest_path(choices):
newlist = []
for s in list(longest_path_from(w, choices) for w in choices):
if s[0][0] == s[-1][-1]:
newlist.append( s )
return max(len(s) for s in newlist)
print(longest_path({'ca','abc','cd','da'}))
longest_path可以變成單線,但那是病態的。;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359896.html
上一篇:串列遞回和字串構建
下一篇:如何在React中遞回渲染帖子
