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

ตรวจสอบว่ามี permutation ของตัวเลขที่เป็นพาลินโดรมและหาร 3 ลงตัว ใน Python


ปัญหา

ให้ตัวเลขใหญ่ N ตรวจสอบว่ามีการจัดเรียงหลักใหม่ที่เป็นพาลินโดรมและหาร 3 ลงตัวหรือไม่

เงื่อนไข

  1. หาร 3 ลงตัว: ผลรวมหลักต้องหาร 3 ลงตัว
  2. เป็นพาลินโดรมได้: หลักที่มีความถี่คี่ ≤ 1 ตัว

ตัวอย่าง

N = 132213 → ผลรวมหลัก = 12 (หาร 3 ลงตัว), ความถี่: 1:2, 2:2, 3:2 → ทุกค่าคู่ → True

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

def solve(N):
    digits = [int(d) for d in str(N)]
    digit_sum = sum(digits)
    
    # เงื่อนไข 1: หาร 3 ลงตัว
    if digit_sum % 3 != 0:
        return "No permutation is a palindrome and is divisible by three"
    
    # เงื่อนไข 2: จัดเป็นพาลินโดรมได้
    from collections import Counter
    freq = Counter(digits)
    odd_count = sum(1 for v in freq.values() if v % 2 == 1)
    
    if odd_count > 1:
        return "No permutation is a palindrome and is divisible by three"
    return "One or more permutation is a palindrome and is divisible by three"

print(solve(132213))
# One or more permutation is a palindrome and is divisible by three

อินพุต / เอาต์พุต

Input:  132213
Output: One or more permutation is a palindrome and is divisible by three