Tìm và in các từ xuất hiện chính xác K lần trong chuỗi, mỗi từ chỉ in một lần.
Ví dụ
Minh họa:
def key_freq_words(my_string, K):
my_list = my_string.split(" ")
for i in my_list:
if my_list.count(i) == K:
print(i)
my_list.remove(i)
my_string = "hi there how are you, how are u"
K = 2
print("Chuỗi:")
print(my_string)
print(f"Từ xuất hiện {K} lần:")
key_freq_words(my_string, K)
Kết quả
Chuỗi: hi there how are you, how are u Từ xuất hiện 2 lần: how are
Giải thích
- Tách chuỗi thành list từ bằng
split(). - Duyệt list, nếu
count(i) == Kthì in vàremove(i)để không in trùng. - Lưu ý: sửa đổi list khi đang duyệt có thể bỏ sót, cách an toàn hơn dùng
Counter.