Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - หาตัวอักษรที่ซ้ำน้อยที่สุดในสตริง

ใช้ collections.Counter นับจำนวนแต่ละตัวอักษร แล้วหาตัวที่มีค่าน้อยที่สุดด้วย min() และ key

ตัวอย่างโค้ด

from collections import Counter

my_str = "highland how"
print("The string is : ")
print(my_str)

my_result = Counter(my_str)
my_result = min(my_result, key=my_result.get)
print("The minimum of all characters in the string is : ")
print(my_result)

ผลลัพธ์

The string is : highland how
The minimum of all characters in the string is : a

คำอธิบาย

  • Counter(my_str) คืน Dict-like: {'h': 3, 'i': 1, 'g': 1, ...}
  • min(counter, key=counter.get) หา Key ที่ Value น้อยที่สุด
  • ถ้ามีหลายตัวเท่ากัน จะคืนตัวแรกที่เจอ (ขึ้นอยู่กับ Python version)
  • รวมช่องว่างด้วย (Space ก็คือ Character)