python - Simpler way to get the list of words that has only 1 letter difference? (python)
问题描述
words = []
for w in wordList:
wcnt = 0
for i in range(len(word)):
if w[i] != word[i]:
wcnt += 1
if wcnt == 1:
words.append(w)
Given a word and a list of strings, I want to retrieve the list of strings that has only one character different from the given word
.
I tried the code above, and it works fine, but it takes too long.
I am practicing an interview, and I prefer not to use any library.
How can I make it simpler?
example)
word = "lost"
wordList= ["most","mist","miss","lost","fist","fish"]
Output should be ['most']
EDIT: only changing 1 character works. Not deleting or adding.
解决方案
The complexity would remain the same, but maybe you could speed it up using sum
inside a list comprehension:
words = [w for w in wordList if sum(a!=b for a,b in zip(word,w)) == 1]
zip
avoids playing with indices by directly interleaving letters and yielding them for one to one comparisonsum
avoids counting natively in python (the expression interleaves letters of both words and adds 1 if different, 0 otherwise, comparison yieldsTrue
orFalse
which are worth 1 and 0 respectively)- list comprehensions are highly optimized python constructs
- the code above doesn't use any external libraries, only built-ins
- it doesn't crash with
IndexError
even if the length of the words differ (even if the results will then be unreliable) becausezip
stops when the shorter sequence ends. - one-liners are cool (when not too far-fetched/with side effects)
so the more builtins you'll use, the faster it will generally get. Here it could probably be slightly improved to stop counting if the number of different letters reaches 2, but it would mean stop using comprehensions.
推荐阅读
- javascript - 如何在intellij中提供“忽略的承诺”警告,但仅限于特定功能?
- google-colaboratory - 错误:目录“。” 不可安装。未找到“setup.py”和“pyproject.toml”
- c# - 如何在 C# .NetFramework 4.0 中执行异步和等待(如在 .NetFramework 5.0 中)?
- node.js - 在 Heroku 中部署 MERN 堆栈应用程序时的问题
- angular - 角度路由:为子 :ID 路径添加前缀
- python - 无法正确导入kivy
- vhdl - 如何减少 Modelsim 中的 WLF 文件大小?
- python - 从两个矩阵的比较中创建新矩阵
- jquery - 仅当内部最后一个 li 具有 .active 时才添加下一个按钮新类
- javascript - 如何将星级值保存到本地存储以及页面重新加载时如何显示?