Exercice 61

Write a program in Python that asks the user to enter five integers of their choice and return them a dictionary whose keys are the entered numbers and whose values are the lists of the divisors of the entered numbers. Example if the user enters the numbers: 14, 7, 8, 6, 13 the program returns the dictionary:

d = {14: [1, 2, 7, 14], 7: [1,7], 8: [1, 2, 4, 8], 6: [1,3,6], 13: [1, 13]}

Solution

# function which determines the list of divisors of an integer
def listDiv (n):
# initialization of the list of divisors of n
l = []
# iterate over integers 1, 2, 3, ..., n
for i in range (1, n + 1):
# if i is a divisor of n we add it to the list
if n%i == 0:
l.append (i)
return l

# retrieving numbers typed in a python list
typed_number = []
for i in range (0, 5):
n = int (input ("Type an integer"))
typed_number.append (n)

# dictionary creation
d = dict ({})
for n in typed_number:
d [n] = listDiv (n)

print(d)
# the output is: {14: [1, 2, 7, 14], 7: [1, 7], 8: [1, 2, 4, 8], 6: [1, 2, 3, 6], 13: [1, 13]}
Younes Derfoufi
my-courses.net

Leave a Reply