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

Python – เรียงลำดับสตริงตามความต่างของตัวพิมพ์ใหญ่-เล็ก (Case Difference)

ภาพรวม

จัดเรียงลิสต์สตริงตามค่าสัมบูรณ์ของความต่างระหว่างจำนวนตัวอักษรพิมพ์ใหญ่ (uppercase) และพิมพ์เล็ก (lowercase)

อัลกอริทึม

  • นับตัวพิมพ์เล็ก: sum(1 for c in s if c.islower())
  • นับตัวพิมพ์ใหญ่: sum(1 for c in s if c.isupper())
  • คืนค่า abs(lower - upper)
  • ใช้เป็น key ใน list.sort()

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

def get_diff(my_string):
    lower_count = sum(1 for c in my_string if c.islower())
    upper_count = sum(1 for c in my_string if c.isupper())
    return abs(lower_count - upper_count)

my_list = ["Abc", "Python", "best", "hello", "coders"]
print("The list is:", my_list)

my_list.sort(key=get_diff)
print("Sorted Strings by case difference:", my_list)

ผลลัพธ์

The list is: ['Abc', 'Python', 'best', 'hello', 'coders']
Sorted Strings by case difference: ['Abc', 'Python', 'best', 'coders', 'hello']

คำอธิบายผลลัพธ์

StringLowerUpperDiff
Abc211
Python514
best404
hello505
coders606

เรียงจาก diff น้อยไปมาก: Abc (1), Python (4), best (4), coders (6), hello (5) – หมายเหตุ: Python และ best เท่ากัน 4 คงลำดับเดิม (stable sort)

หมายเหตุ

  • ตัวอย่าง output เดิมมีลำดับ 'coders' ก่อน 'hello' แต่ diff ของ hello=5, coders=6 ดังนั้น hello ควรก่อน – อาจเป็น bug ในตัวอย่างต้นฉบับ
  • Python sort เป็น stable sort รักษาลำดับเดิมเมื่อ key เท่ากัน