Python-courses-download-Python-courses-s-Python-courses

Exercise 48

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

Solution

def oddSum (L):
n = len (L)
# initialize the sum of elements with odd index
s = 0
# browsing throw elements of L and searching all elements of with odd index
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)) # the output is 17
Younes Derfoufi
my-courses.net

Leave a Reply