Python-courses-python-exercises-python--Python-courses-configure script-run-script

Exercise 47

Write a Python algorithm as a function that takes a list L as a parameter and returns the sum of elements of the list L with odd index. Example if L = [3, 2, 5, 11, 21, 4, 7], the algorithm returns the number L[1] + L[3] + L[5] = 2 + 11 + 4 = 17.

Solution

def oddSum (L):
n = len (L)
# initialize the sum of elements with odd index
s = 0
for i in range (0, n):
if i% 2 != 0:
s = s + L [i]
return s
# Example
L = [3, 2, 5, 11, 21, 4, 7]
print (oddSum (L)) # prints 17
Younes Derfoufi
my-courses.net

Leave a Reply