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

วิธีหา Keith Numbers ด้วย Python

ใช้โค้ดต่อไปนี้ตรวจสอบว่าเลขเป็น Keith number ใน Python

ตัวอย่าง

def is_keith_number(n):
    # หาผลรวมหลักด้วยการแปลงเป็นอาร์เรย์หลักแล้วบวก
    c = str(n)
    a = list(map(int, c))
    b = sum(a)
    # ตรวจสอบว่าเป็น Keith number
    # เช่น 14 เป็น Keith number เพราะ:
    # 1+4 = 5
    # 4+5 = 9
    # 5+9 = 14
    while b < n:
        a = a[1:] + [b]
        b = sum(a)
    return (b == n) & (len(c) > 1)

print(is_keith_number(14))

ผลลัพธ์

True