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

เขียนโปรแกรม Python กรองเลขอาร์มสตรอง (Armstrong numbers) ใน Series

สมมติว่าคุณมี Series ของตัวเลข และต้องการกรองเฉพาะเลขอาร์มสตรอง (Armstrong numbers) - เลขที่เท่ากับผลรวมของตัวเลขแต่ละหลักยกกำลังจำนวนหลัก

วิธีแก้ปัญหา

  1. สร้าง Series
  2. วนลูปตรวจสอบแต่ละค่า ว่าเป็น Armstrong number หรือไม่
  3. เก็บค่าที่เป็น Armstrong ไว้ใน list
  4. ใช้ data[data.isin(list)] กรอง Series เดิม

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

import pandas as pd

data = pd.Series([153, 323, 371, 420, 500])
print("Series ต้นฉบับ:\n", data)

armstrong_list = []
for val in data:
    armstrong = 0
    temp = val
    # คำนวณผลรวมเลขยกกำลัง 3 (เพราะเป็นเลข 3 หลัก)
    while temp > 0:
        rem = temp % 10
        armstrong += rem ** 3
        temp //= 10
    if armstrong == val:
        armstrong_list.append(val)

print("\nเลขอาร์มสตรองที่พบ:")
print(data[data.isin(armstrong_list)])

ผลลัพธ์

Series ต้นฉบับ:
0    153
1    323
2    371
3    420
4    500
dtype: int64

เลขอาร์มสตรองที่พบ:
0    153
2    371
dtype: int64

คำอธิบาย:

  • Armstrong number (Narcissistic number): เลข n หลัก ที่เท่ากับผลรวมของแต่ละหลักยกกำลัง n
  • ตัวอย่าง: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓
  • 371 = 3³ + 7³ + 1³ = 27 + 343 + 1 = 371 ✓
  • โค้ดนี้คำนวณเฉพาะกำลัง 3 (สำหรับเลข 3 หลัก) ถ้าต้องการรองรับทุกหลัก ต้องนับจำนวนหลักก่อน