Exercise 3
Write a python algorithm as a function which takes a list l as parameters and returns a tuple of two lists (l_even, l_odd) where l_even is made up of the elements of l with an even index and l_old is made up of the elements with an odd index. Example: if: L = ["Python", "Java", "C++", "C#", "VB.Net", "Javascript"], the algorithm returns: (['Python', 'C++', 'VB .Net'], ['Java', 'C#', 'Javascript'])
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def odd_event(L): # get length of list n = len(L) # initialization of the lists of odd index and even index l_odd = [] l_even = [] # build the l_odd and l_even lists for i in range(0, n): if( i%2 == 0): l_even.append(L[i]) else: l_odd.append(L[i]) return (l_even, l_odd) # Example L = ["Python", "Java", "C++", "C#", "VB.Net", "Javascript"] print(odd_event(L)) # Output is: (['Python', 'C++', 'VB.Net'], ['Java', 'C#', 'Javascript']) |
Younes Derfoufi
CRMEF OUJDA
1 thought on “Solution Exercise 3: python algorithm that determines the list of odd index items and the list of even index items”