Wednesday, September 23, 2020

Solution Exercise 105: algorithm python to generate a dictionary from given number

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

Python Exercises With Solutions

1. Python Arithmetic Exercises
2. Equations & System Of Equations
3. Polynomials and Functions
4. Python Arithmetic Exercises
5. Numpy, Matplolib, Sympy , Scipy - Exercises
6. Python Arithmetic Exercises

Younes Derfoufi