เมื่อต้องการตรวจสอบว่าความถี่ของตัวอักษรในสตริงสามารถทำให้เท่ากันได้โดยการลบตัวอักษรออกได้สูงสุด 1 ตัว ใช้ Counter นับความถี่ แล้วตรวจสอบเงื่อนไข
ตัวอย่างโค้ด
from collections import Counter
def check_frequencies(s):
freq = Counter(s)
freq_values = list(set(freq.values()))
if len(freq_values) > 2:
print('The frequencies are not same')
elif len(freq_values) == 2 and abs(freq_values[1] - freq_values[0]) > 1:
print('The frequencies are not same')
else:
print('The frequencies are same')
my_str = 'xxxyyyzzzzzz'
print("The string is:", my_str)
check_frequencies(my_str)ผลลัพธ์
The string is: xxxyyyzzzzzz The frequencies are not same
คำอธิบาย
Counter(s)นับความถี่แต่ละตัวอักษร: {'x':3, 'y':3, 'z':6}set(freq.values())ได้ค่าความถี่ที่ไม่ซ้ำ: {3, 6}ถ้ามีค่าความถี่มากกว่า 2 ค่า → ไม่สามารถทำให้เท่ากันได้
ถ้ามี 2 ค่า และต่างกันมากกว่า 1 → ไม่สามารถทำให้เท่ากันได้ (ลบ 1 ตัวไม่พอ)
กรณี 'xxxyyyzzzzzz': ความถี่ 3 และ 6 ต่างกัน 3 → Not same