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

Python – หาตัวเลขที่หารลงตัวด้วยทุกค่าใน List ที่กำหนด (Multiples of All Divisors)

ภาพรวม

จาก list ของตัวเลข ให้คัดเฉพาะตัวที่หารด้วย ทุกค่า ใน divisor list ลงตัว (remainder = 0)

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


my_list = [45, 67, 89, 90, 10, 98, 10, 12, 23]
my_division_list = [6, 4]

print("The list is:", my_list)
print("The division list is:", my_division_list)

my_result = [
    element for element in my_list
    if all(element % d == 0 for d in my_division_list)
]

print("The result is:", my_result)

ผลลัพธ์

The list is: [45, 67, 89, 90, 10, 98, 10, 12, 23]
The division list is: [6, 4]
The result is: [12]

คำอธิบาย

  • 90 % 6 = 0 แต่ 90 % 4 = 2 -> ไม่ผ่าน
  • 12 % 6 = 0 และ 12 % 4 = 0 -> ผ่าน
  • ตัวอื่นไม่ผ่านเงื่อนไขทั้งคู่

Mathematical Insight

การหารลงตัวด้วย 6 และ 4 พร้อมกัน = หารลงตัวด้วย LCM(6, 4) = 12


import math
lcm = math.lcm(*my_division_list)  # Python 3.9+
my_result = [x for x in my_list if x % lcm == 0]

ประยุกต์: FizzBuzz แบบกำหนดเอง


def custom_fizzbuzz(numbers, divisors_words):
    for n in numbers:
        words = [w for d, w in divisors_words if n % d == 0]
        print(''.join(words) if words else n)

custom_fizzbuzz(range(1, 21), [(3, "Fizz"), (5, "Buzz"), (7, "Bang")])