Solution Exercise 107: python program to create dictionary containing list of integers as keys and lits of their divisors as values

Sep 24, 2020

Exercise 107

Write a program in Python that asks the user to enter ten integers of their choice and return them a dictionary whose keys are the integers entered and whose values ​​are the lists of divisors of the numbers entered. Example if the user enters the numbers: 2, 7, 11, 5, 3, 19, 14, 9, 1, 4, the program returns the dictionary:

``d = {2: [1,2], 7: [1,7], 14: [1,2,7,14],     9: [1,3,9], 11: [1,11], 5: [1,5],     3: [1,3], 19: [1,19], 1: [1], 4: [1,2,4]}``

Solution

``# create a function that find the list of divisor for given integerdef listDivisors(n):    # Initializing th list of divisors     listDiv =[]    # browsing through all integers from 1 to n     # and then we tst if i is a divisor of n    for i in range(1,n+1):        if n%i == 0:            listDiv.append(i)    return listDiv  # create an empty dictionary which will receive the values of typed integersd = dict({})for i in range(1 , 11):    # asking user to enter value of intger n    n = int(input("Enter value of integer n : " ))        # adding n and list of divisors of n t the dictionary d    d[n] = listDivisors(n)# display generated dictionar dprint("The dictionary is : d = ", d)#testing algorithm# for typed integer : # the output is : 8, 12, 10, 6 , 3, 9, 22 , 11 , 17, 15# The dictionary is : d =  {8: [1, 2, 4, 8], 12: [1, 2, 3, 4, 6, 12], 10: [1, 2, 5, 10], 6: [1, 2, 3, 6], 3: [1, 3], 9: [1, 3, 9], 22: [1, 2, 11, 22], 11: [1, 11], 17: [1, 17], 15: [1, 3, 5, 15]}``

Younes Derfoufi
my-courses.net