Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để tìm số keith bằng Python?


Bạn có thể sử dụng mã sau để tìm xem một số có phải là số keith trong python -

Ví dụ

def is_keith_number(n):
   # Find sum of digits by first getting an array of all digits then adding them
   c = str(n)
   a = list(map(int, c))
   b = sum(a)

   # Now check if the number is a keith number
   # For example, 14 is a keith number because:
   # 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))

Đầu ra

Điều này sẽ cung cấp đầu ra -

True