Question

""" ''' Write a python code to push all zeors to the end of an array...

"""
'''
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?

Homework Answers

Answer #1

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..

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Language: Python Write a program to simulate an experiment of tossing a fair coin 16 times...
Language: Python Write a program to simulate an experiment of tossing a fair coin 16 times and counting the number of heads. Repeat this experiment 10**5 times to obtain the number of heads for every 16 tosses; save the number of heads in a vector of size 10**5 (call it headCounts). You should be able to do this in 1-3 lines of numpy code. (Use np.random.uniform1 to generate a 2d array of 10**5 x 16 random numbers between 0 and...
convert this code to accept int value instead of float values using python. Make sure to...
convert this code to accept int value instead of float values using python. Make sure to follow the same code. do not change the steps and make sure to point to what code you replaced. make sure to have 2 files Method:----------------------- #define a python user difined method def get_float_val (prompt): is_num = False str_val = input (prompt) #prming read for our while #while is_num == False: (ignore this but it works) old school while not is_num: try: value =...
This is my code, python. I have to search through the roster list to find a...
This is my code, python. I have to search through the roster list to find a player using their number. it says list index out of range. it also says there is error in my main. def file_to_dictionary(rosterFile): myDictionary={}       with open(rosterFile,'r') as f: data=f.read().split('\n')       for line in data:    (num,first,last,position)=line.split() myDict=[first, last, position] myDictionary[num]=myDict print (myDictionary) return myDictionary file_to_dictionary((f"../data/playerRoster.txt"))    def find_by_number(number): player=None    second=[] foundplayer= False myDictionary=file_to_dictionary((f"../data/playerRoster.txt")) for p in myDictionary: fullplayer=p.split() second.append([fullplayer[0], (fullplayer[1]+" "+...
So, i have this code in python that i'm running. The input file is named input2.txt...
So, i have this code in python that i'm running. The input file is named input2.txt and looks like 1.8 4.5 1.1 2.1 9.8 7.6 11.32 3.2 0.5 6.5 The output2.txt is what i'm trying to achieve but when the code runs is comes up blank The output doc is created and the code doesn't error out. it should look like this Sample Program Output 70 - 510, [semester] [year] NAME: [put your name here] PROGRAMMING ASSIGN MENT #2 Enter...
I am working on exercise 5.30 from Introduction to Computing using python (Author: Perkovic). I was...
I am working on exercise 5.30 from Introduction to Computing using python (Author: Perkovic). I was looking at the solution and was able to understand what to do. However, when I implement the temp function as indicated, I keep getting this error "ValueError: the first two maketrans arguments must have equal length". However, it seems my two arguments are equal length, so I'm not sure what I am doing wrong! print('Exercise 5.30') def many(file): infile = open(file) content = infile.read()...
Plotting trajectories Classical Mechanics (Python) Question: In the plot, set v = 1 m/s, ω =...
Plotting trajectories Classical Mechanics (Python) Question: In the plot, set v = 1 m/s, ω = 1 1/s, and plot the trajectory for t ∈ [−6π, 6π]. Code: import numpy as np import matplotlib.pyplot as plt tx=[] for i in range(180): tx.append(i) radianConverter = np.pi/180 x_2 = [1*t*np.cos(2*np.pi*t*radianConverter) for t in tx] y_2 = [1*t*np.sin(2*np.pi*t*radianConverter) for t in tx] plt.figure(figsize=[10,10]) plt.grid(True) plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') plt.plot(x_2,y_2) plt.show() What changes do I have to do in order to fit the question...
python 3 For this exercise you are to implement the function poly_iter in the array-backed list...
python 3 For this exercise you are to implement the function poly_iter in the array-backed list class, which, when called with positive integer parameters a, b, c, returns an iterator over the values in the underlying list at indexes a*i2+b*i+c, for i=0, 1, 2, ... E.g., given an array-backed list lst containing the elements [0, 1, 2, 3, 4, ..., 98, 99], the following code: for x in lst.poly_iter(2, 3, 4): print(x) will produce the output: 4 9 18 31...
write a code in python Write the following functions below based on their comments. Note Pass...
write a code in python Write the following functions below based on their comments. Note Pass is a key word you can use to have a function the does not do anything. You are only allowed to use what was discussed in the lectures, labs and assignments, and there is no need to import any libraries. #!/usr/bin/python3 #(1 Mark) This function will take in a string of digits and check to see if all the digits in the string are...
Code in Python Hello I need an os module to restart and re-run the whole code...
Code in Python Hello I need an os module to restart and re-run the whole code when the multiplier limit is reached. So when the code stops the outputs I need it to initialize again. import os, sys initial=int(input("Initial value : "))       #taking inputs multiplier=float(input("Multiplier : ")) compound=int(input("No of compounds : ")) print("Your values are:") mult=initial                         #initalizing to find answer for i in range(0,compound):         #multiplying by multiplier     print(round(mult,1))     mult=mult*multiplier
How do I fix my code to collect ONLY hashtag instead of accumulating all the information...
How do I fix my code to collect ONLY hashtag instead of accumulating all the information about the number of occurrences of all words from the textfile? Please help to fix below codes. tweetcount=0 maxcount=0 count = 0 with open('elon-musk.txt') as book: for tweet in book: count += 1 print("Number of tweets:", count) print() with open('elon-musk.txt') as book: for line in book: s count = len(line.split()) if count>maxcount: maxline = line maxcount = count tweetcount += 1 print("Tweet with max...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT