Python-courses-python-exercises

Exercise 42

Write a Python algorithm as a function which takes as a parameter a list of integers L and which returns the list obtained from L by inserting just after each number the string 'even' or 'odd' depending on the parity of number. Example if L = [2, 11, 25, 6, 14], the algorithm returns the list: [2, 'even', 11, 'odd', 25, 'odd', 6, 'even', 14, 'even']

Solution

def listEvenOdd (L):
# initialization of the searched list
lEventOdd = []
for n in L:
# Add the element n to the list
lEventOdd.append(n)
if n% 2 == 0:
lEventOdd.append ('even')
else:
lEventOdd.append ('odd')

return lEventOdd

# Example
L = [21, 12, 54, 71, 13, 20]
print (listEvenOdd (L))
# [21, 'odd', 12, 'even', 54, 'even', 71, 'odd', 13, 'odd', 20, 'even']
Younes Derfoufi
my-courses.net

Leave a Reply