0

## Python_最短單詞距離

QQ 2021-04-13 17:25:03841 瀏覽

（其中 "a" 有重複，index 分別是2,5,8，所以最短距離為3。）

``````input：words = ["I","am","a","student","from","a","university","in","a","city"]
output：3
``````

``````import sys
def find_nearest_repeated_word(s:list, word1:str, word2:str)->int:

if s == None or word1 == None or word2 == None:
return -1

idx1 = -1
idx2 = -1
minDiff = sys.maxsize

for i in range(len(s)):
if s[i] == word1:
idx1 = i

if s[i] == word2:
idx2 = i

if idx1 != -1 and idx2 != -1:
minDiff = min(minDiff, abs(idx1 - idx2))

return minDiff
``````

``````print(find_nearest_repeated_word(["I","am","a","student","from","a","university","in","a","city"]))
ANS = 3
``````
tunin iT邦新手 5 級 ‧ 2021-04-13 18:30:40 檢舉

### 1 個回答

3

iT邦大師 1 級 ‧ 2021-04-13 22:38:26

``````from collections import defaultdict
import itertools

words = ["I","am","a","student","from","a","university","in","a","city"]

d = defaultdict(list)

for i in range(len(words)):
d[words[i]].append(i)

print(sorted(d.items()))
print()

new_dict = {}

for k, v in d.items():
if len(v) > 1:
new_dict[k] = v

print(new_dict)
print('-' * 10)

for k, v in new_dict.items():
new_list = []
p = itertools.product(v,v)
for v1, v2 in p:
if v1 != v2 :
new_list.append(abs(v1 - v2))

short = min(new_list)
print(k , '(short distance)--> ', short)

``````

``````python3 p0413.py
[('I', [0]), ('a', [2, 5, 8]), ('am', [1]), ('city', [9]), ('from', [4]), ('in', [7]), ('student', [3]), ('university', [6])]

{'a': [2, 5, 8]}
----------
a (short distance)-->  3
``````

QQ iT邦新手 5 級 ‧ 2021-04-14 00:36:35 檢舉