Trong câu có từ lặp lại trước khi kết thúc. Chương trình bắt từ lặp đầu tiên. Các bước:
- Tách chuỗi thành từ bởi khoảng trắng.
- Chuyển thành Dictionary dùng collections.Counter.
- Duyệt list từ, kiểm tra từ đầu tiên có frequency > 1.
Chương trình
from collections import Counter
def Repeat_word(load):
word = load.split(' ')
dict = Counter(word)
for value in word:
if dict[value] > 1:
print(value)
return
if __name__ == "__main__":
input = 'In good time in bad time friends are friends'
Repeat_word(input)
Kết quả
time