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

วิธีพิมพ์ Narcissistic (Armstrong) Numbers ด้วย Python

เพื่อพิมพ์ Narcissistic Numbers มาดูความหมายก่อน คือเลขที่เท่ากับผลรวมของหลักตัวเองแต่ละหลักยกกำลังจำนวนหลัก เช่น 1, 153, 370 เป็น Narcissistic numbers พิมพ์ได้ด้วยโค้ดนี้

def print_narcissistic_nums(start, end):
    for i in range(start, end + 1):
        # ดึงหลักตัวเลขในลิสต์
        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)

ผลลัพธ์

1 2 3 4 5 6 7 8 9 153 370 371