"""
'''
Write a python code to
push all zeors to the end of an array
'''
import numpy as np
def Move_a(i):
num = len(a)
for k in range (i, num-1):
a[k] = a[k+1]
a[num-1] = 0
return a
a = np.array([0,1,4,7,0,9,12,0,0,15,0,21])
#length of array (len)
num = len(a)
print (num)
for i in range(0,num):
if (a[i] == 0):
#Functioon call to Move_a()
a = Move_a(i)
print ("the array looks like")
print (a)
My code is able to push all zeros to the end of the array, but
does not work if two zeros are next to each other. How do I fix
this?
change in your code...
Another O(n) time approach...Simplest..
import numpy as np
a = np.array([0,1,4,7,0,9,12,0,0,15,0,21])
num = len(a)
j = 0
for i in range(0,num):
if (a[i] != 0):
a[i],a[j] = a[j],a[i] # swap...
j+=1
print ("the array looks like")
print (a)
plz like it...if u have still
any query u can ask through comment..
Get Answers For Free
Most questions answered within 1 hours.