Tuple of distinct divisors of numbers in a list in Python


This Python code processes the numbers list and creates a tuple called distinct_divisors. Each element in this tuple is a set of distinct divisors for a number from the numbers list. Here's how the code works:

  • numbers = [10, 15, 20, 25]: This line initializes a variable named numbers and assigns it a list containing four numbers.
  • distinct_divisors = tuple({divisor for divisor in range(1, num+1) if num % divisor == 0} for num in numbers): This line initializes a variable named distinct_divisors and assigns it a tuple created using a generator expression.
    • for num in numbers: This part of the code sets up a loop that iterates through each number num in the numbers list.
    • {divisor for divisor in range(1, num+1) if num % divisor == 0}: For each number, it creates a set of distinct divisors. It does this by using a set comprehension that iterates through numbers from 1 to num, checking if num is divisible by each number divisor using the condition num % divisor == 0.
    • tuple(...): This surrounds the generator expression and converts the generated sets of distinct divisors into a tuple.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(distinct_divisors): This line of code prints the distinct_divisors tuple (which contains sets of distinct divisors for each number) to the console.

Source Code

numbers = [10, 15, 20, 25]
distinct_divisors = tuple({divisor for divisor in range(1, num+1) if num % divisor == 0} for num in numbers)
print(numbers)
print(distinct_divisors)

Output

[10, 15, 20, 25]
({1, 2, 10, 5}, {1, 3, 5, 15}, {1, 2, 4, 5, 10, 20}, {1, 5, 25})

Example Programs