Cho chuỗi tên công ty. Tìm 3 ký tự xuất hiện nhiều nhất, sắp xếp:
- Giảm dần theo tần suất.
- Nếu tần suất bằng nhau, tăng dần theo thứ tự bảng chữ cái.
Ví dụ: "TUTORIALSPOINT" → [[3, 'T'], [2, 'I'], [2, 'O']].
Cách làm
- Dùng
Counterđếm tần suất. - Tạo list các cặp
[count, char]. - Sắp xếp 2 lần: trước theo ký tự (alphabet), sau theo count giảm dần (stable sort đảm bảo thứ tự alphabet khi count bằng nhau).
- Lấy 3 phần tử đầu.
Ví dụ mã nguồn
from collections import Counter
def solve(s):
x = Counter(s)
res = [[x[i], i] for i in x]
res = sorted(res, key=lambda cnt: cnt[1]) # alphabet
res = sorted(res, key=lambda cnt: cnt[0], reverse=True) # frequency desc
return res[:3]
s = "TUTORIALSPOINT"
print(solve(s)) # [[3, 'T'], [2, 'I'], [2, 'O']]
Đầu vào / Đầu ra
Input: "TUTORIALSPOINT"
Output: [[3, 'T'], [2, 'I'], [2, 'O']]