I’m trying to find all the letters in a list that differ from each other by word. I then output them into an array. The trouble is it takes my current code 17 seconds for 18, 000 words and I trying to cut down the time it takes.
Is there anyway I can speed this up?
#compares words and returns true if they are neighbours
def isneighbour(word1, word2):
diff = 0
for i in range(len(word1)):
if word1[i] != word2[i]:
diff += 1
if diff > 1:
return False
return diff == 1
def find_neighbours(lst):
#take a word from lst
#compare to rest of words from lst
hood = []
#convert dictionary to list
#search for all words of same length
keylst = list(lst.keys())
length = len(keylst) -1
for i in range(0, length -1):
temp = []
temp.append(keylst[i])
for j in range(i + 1, length):
if len(keylst[i]) == len(keylst[j]):
#test to see if two words of the same length are neighbours
if isneighbour(keylst[i], keylst[j]):
temp.append(keylst[j])
if len(temp)>1:
quicksort(temp)
hood.append(temp)
return hood
I’ve had a google around and can’t see how I can improve on this. I am student, so all suggestions will be useful.
New contributor
Gijoel2001 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.