I'm doing a coding problem where the aim is to "write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred."
I'm testing my code in Python, and running into a problem where I'm setting a condition to ignore 0's when I find them, but the condition is not working. Is it because I'm modifying the list in the loop, and it is not considering the updated values? Can I handle this without extra space?
def remove_zeros(array):
for i in range(len(array)):
if array[i] != 0 or array[i] != "0":
c = array[i]
print(c) #this is printing 0, but I'm setting condition to ignore 0's!
for j in range(i, 0, -1):
if array[j - 1] == 0 or array[j - 1] == "0":
temp = array[j]
array[j] = array[j - 1]
array[j - 1] = temp
return array
input = [ 1, None, '5', '0', '2', 0, 8, 6, None, False ]
output = remove_zeros(input)