Python-courses-python-exercises-python-exception-python-pip

Exercise 44

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 moving all zeros to the beginning of the list. Example if L = [7, 0, 11, 0, 25, 16, 0, 14], the algorithm returns the list: [0, 0, 0, 7, 11, 25, 16, 14]

Solution

def moveZero(L):
# list extracted from L formed only of zeros from L
l_zero = []
# list extracted from L formed only of the non-zero elements of L
l_without_zero = []
for x in L:
if x == 0:
l_zero.append(x)
else:
l_without_zero.append (x)
return l_zero + l_without_zero

# Example:
L = [7, 0, 11, 0, 25, 16, 0, 14]
print (moveZero(L)) # print: [0, 0, 0, 7, 11, 25, 16, 14]
Younes Derfoufi
my-courses.net

Leave a Reply