Để in số Narcissistic, trước hãy xem định nghĩa. Là số bằng tổng các chữ số của nó mỗi chữ số lũy thừa theo số chữ số. Ví dụ, 1, 153, 370 là số Narcissistic. Bạn in các số này bằng code sau
def print_narcissistic_nums(start, end): for i in range(start, end + 1): # Lấy chữ số từ số trong list: digits = list(map(int, str(i))) total = 0 length = len(digits) for d in digits: total += d ** length if total == i: print(i) print_narcissistic_nums(1, 380)
Kết quả
1 2 3 4 5 6 7 8 9 153 370 371