Python好在哪裡?[日常]

無意中看到一個題目:

給出一個單詞,找出一組單詞中,跟該單詞最匹配的一個。

於是我就想到了Levenshtein Distance (LD)演算法(編輯距離演算法),然後用Python實現了一個:

class Dictionary: def __init__(self, words): self.words=words def find_most_similar(self, term): import sys def measure(term, item): tc = [t for t in term] # row ic = [i for i in item] # column mt = [[i if t == 0 else t if i == 0 else None for i in range(len(ic)+1)] for t in range(len(tc)+1)] for i in range(1, len(mt)): for j in range(1, len(mt[0])): f = 1 if tc[i-1] != ic[j-1] else 0 mt[i][j] = min(mt[i-1][j]+1, mt[i][j-1]+1, mt[i-1][j-1]+f) return mt[-1][-1] result = [None, sys.maxsize] for item in self.words: distance = measure(term, item) if distance < result[1]: result = [item, distance] return result[0]words=[cherry, peach, pineapple, melon, strawberry, raspberry, apple, coconut, banana]d = Dictionary(words)d.find_most_similar(strawbery)d.find_most_similar(berry)d.find_most_similar(aple)

但是,等等!然後又發現,Python的difflib

6.3. difflib - Helpers for computing deltas - Python 3.6.4 documentation?

docs.python.org

已經幫你實現了:

import difflibwords=[cherry, peach, pineapple, melon, strawberry, raspberry, apple, coconut, banana]difflib.get_close_matches(strawbery, words)[0]difflib.get_close_matches(berry, words)[0]difflib.get_close_matches(aple, words)[0]

愛死Python了。最近看到很多棄Python轉投Go、Java啥的消息,我感覺如果Python能搞定的,還是盡量用Python吧。在團隊規約方面投入更多力氣的代價,比轉其他編程語言值得呀。

推薦閱讀:

現在學編程,晚么?
C++程序設計(一):數據的存儲,形式和運算
決定入駐知識星球
工作中遇到很讓人頭疼的上司怎麼辦?

TAG:Python | 編程 | 軟體開發 |