Exercise 105

Write a function in Python that takes a list of integers as a parameter and returns a dictionary whose keys are the list integers and whose values are "even" or "odd" depending on the number parity.

Solution

def listToDict(l):

#create an empty dictionary to retrieve the results
dictParity = dict()

# iterate over the list elements and test their parity
for x in l:
if x%2 == 0:
dictParity[x] = 'Pair'
else:
dictParity[x] = 'Impair'
return dictParity
# Testing algorithm
l = [24 , 14 , 3 , 36 , 41 , 22 , 15]
print(listToDict(l))
# The output is : {24: 'Pair', 14: 'Pair', 3: 'Impair', 36: 'Pair', 41: 'Impair', 22: 'Pair', 15: 'Impair'}

Younes Derfoufi
my-courses.net

Leave a Reply