Create a dictionary of numbers with their divisors


Creates a dictionary named divisors that maps each number in the numbers list to a list of its divisors. Here's how the code works:

  • numbers = [1, 2, 3, 4, 5]: This line initializes the numbers list with a sequence of integers.
  • divisors = {x: [i for i in range(1, x + 1) if x % i == 0] for x in numbers}: This line uses a dictionary comprehension to create the divisors dictionary. Here's what happens:
    • for x in numbers: This part of the code iterates over each number x in the numbers list.
    • {x: ...}: This part of the code creates key-value pairs in the dictionary. The key is the number x, and the value is the result of the inner list comprehension.
    • [i for i in range(1, x + 1) if x % i == 0]: This is the list comprehension that generates a list of divisors for each number x. It iterates through numbers from 1 to x (inclusive) and checks if x is divisible by i. If it is, i is included in the list of divisors.
  • print(numbers): This line prints the numbers list to the console.
  • print(divisors): This line prints the divisors dictionary, which contains numbers as keys and lists of divisors as values.

Source Code

numbers = [1, 2, 3, 4, 5]
divisors = {x: [i for i in range(1, x + 1) if x % i == 0] for x in numbers}
print(numbers)
print(divisors)

Output

[1, 2, 3, 4, 5]
{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 2, 4], 5: [1, 5]}

Example Programs