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

เรียง Matrix ตามจำนวน Palindrome ในแต่ละแถว

แนวคิด

นับจำนวน palindrome (คำอ่านจากหน้าหลังเหมือนกัน) ในแต่ละแถว แล้วเรียงแถวตามจำนวนน้อยไปมาก

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

def get_palindrome_count(row):
    """นับ palindrome ในแถว (row เป็นลิสต์ของสตริง)"""
    return len([elem for elem in row if elem == elem[::-1]])

my_list = [
    ["abcba", "hdgfue", "abc"],
    ["peep"],
    ["py", "is", "best"],
    ["sees", "level", "non", "noon"]
]

print("Matrix:", my_list)

my_list.sort(key=get_palindrome_count)
print("เรียงตามจำนวน palindrome:", my_list)

ผลลัพธ์

Matrix: [['abcba', 'hdgfue', 'abc'], ['peep'], ['py', 'is', 'best'], ['sees', 'level', 'non', 'noon']]
เรียงตามจำนวน palindrome: [['py', 'is', 'best'], ['abcba', 'hdgfue', 'abc'], ['peep'], ['sees', 'level', 'non', 'noon']]

คำอธิบาย

  • แถว 0: abcba(✓), hdgfue(✗), abc(✗) -> 1 palindrome
  • แถว 1: peep(✓) -> 1 palindrome
  • แถว 2: ไม่มี -> 0 palindrome
  • แถว 3: sees, level, non, noon ทั้ง 4 ตัว -> 4 palindromes
  • เรียง 0, 1, 1, 4

ฟังก์ชัน palindrome แบบละเอียด

def is_palindrome(s):
    return s == s[::-1]

# ใช้กับข้อมูลที่ไม่ใช่สตริง (แปลงก่อน)
def get_palindrome_count(row):
    return sum(1 for elem in row if str(elem) == str(elem)[::-1])