Python 找出英文單詞列表(list)中最長單詞鏈
本文主要介紹Python中單詞字符串的列表(list),找出列表中所有單詞中前一個單詞首字母和后一個單詞尾字母相同,組成最長的單詞鏈方法代碼,并且每個單詞不能多次使用。
例如:
words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse']
最長的單詞鏈列表:
['hedgehog', 'giraffe', 'elephant', 'tiger', 'racoon']
1、用遞歸方法查找
words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse'] def get_results(_start, _current, _seen): if all(c in _seen for c in words if c[0] == _start[-1]): yield _current else: for i in words: if i[0] == _start[-1]: yield from get_results(i, _current+[i], _seen+[i]) new_d = [list(get_results(i, [i], []))[0] for i in words] final_d = max([i for i in new_d if len(i) == len(set(i))], key=len)
輸出結果:
['hedgehog', 'giraffe', 'elephant', 'tiger', 'racoon']
2、使用networkx查找
import networkx as nx import matplotlib.pyplot as plt words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse'] G = nx.DiGraph() G.add_nodes_from(words) for word1 in words: for word2 in words: if word1 != word2 and word1[-1] == word2[0]: G.add_edge(word1, word2) nx.draw_networkx(G) plt.show() print(nx.algorithms.dag.dag_longest_path(G))
到此這篇關于Python 找出英文單詞列表(list)中最長單詞鏈的文章就介紹到這了,更多相關Python 列表最長單詞鏈內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- 解決python列表list中的截取問題
- Python3 列表list合并的4種方法
- python中列表(list)和元組(tuple)的深入講解
- Python列表排序 list.sort方法和內(nèi)置函數(shù)sorted用法
- Python 列表(List)的底層實現(xiàn)原理分析
- Python Pandas list列表數(shù)據(jù)列拆分成多行的方法實現(xiàn)
- 深入了解python列表(LIST)
- python 解決mysql where in 對列表(list,,array)問題
- Python將二維列表list的數(shù)據(jù)輸出(TXT,Excel)
- python的列表List求均值和中位數(shù)實例
- Python3列表List入門知識附實例
- Python列表list操作相關知識小結
- 基于python的列表list和集合set操作
- Python List列表對象內(nèi)置方法實例詳解
- Python列表list常用內(nèi)建函數(shù)實例小結
- 詳細整理python 字符串(str)與列表(list)以及數(shù)組(array)之間的轉換方法
- python創(chuàng)建與遍歷List二維列表的方法
- Python源碼解析之List
相關文章
Python argparse模塊實現(xiàn)解析命令行參數(shù)方法詳解
argparse 是 python 自帶的命令行參數(shù)解析包,可以用來方便的服務命令行參數(shù)。本文將通過示例和大家詳細講講argparse的使用,需要的可以參考一下2022-09-09Python實現(xiàn)簡單的列表冒泡排序和反轉列表操作示例
這篇文章主要介紹了Python實現(xiàn)簡單的列表冒泡排序和反轉列表操作,涉及Python列表遍歷、排序、追加等相關操作技巧,需要的朋友可以參考下2019-07-07pandas按若干個列的組合條件篩選數(shù)據(jù)的方法
下面小編就為大家分享一篇pandas按若干個列的組合條件篩選數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04淺析Python中正則表達式函數(shù)search()和match()的使用
在Python中,正則表達式是處理字符串的強大工具,search()和match()是Python標準庫中re模塊中兩個常用的正則表達式方法,本文將詳細講解這兩個方法的使用,需要的可以參考一下2023-08-08python使用redis實現(xiàn)消息隊列(異步)的實現(xiàn)完整例程
本文主要介紹了python使用redis實現(xiàn)消息隊列(異步)的實現(xiàn)完整例程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-01-01