Exercise 83

Write a python algorithm which replaces the elements of even index by 2 and the elements of odd index by 1.

Solution

Solution

# function which replaces the elements of even index by 2 and the elements of odd index by 1
def replace (L):

# initialization of the searched list
list_2_1 = []

for i in range (0, len (L)):
if i% 2 == 0:
list_2_1.append (2)
else:
list_2_1.append (1)
return list_2_1

# Example
L = ["Python", "Java", "C ++", "C #", "Javascript"]
print (replace (L)) # print: [2, 1, 2, 1, 2]
Younes Derfoufi
my-courses.net

Leave a Reply