In: Computer Science
(Programming Language: Python)
It's trivial that the value of a number remains the same no matter how many zeros precede it. However, adding the zeros at the end of the number increases the value * 10. Jasmine is tired of seeing \001/100" on her tests (well yes, no one really writes 001, but Jasmine's teacher finds it funny to do so). So, she managed to login to her teacher's computer and now wants to design a function that can move the 0's in her grade to the end before her teacher uploads her grades. Although we don't agree with Jasmine's tactics, Krish (Jasmine's mentor) told us to help her out by finishing the `move zeros' function. This function should move all the 0's in the given list to the end while preserving the order of the other elements.
Remember that this function needs to modify the list, not return a new list!
---------------------------------------------
def move_zeros(lst: List[int]) -> None:
"""
Move all the 0's in lst to the END of the lst *in-place*, i.e. *modify* the list, DONT return a new list
>>> lst = [1, 0, 2, 3]
>>> move_zeros(lst)
>>> lst [1, 2, 3, 0]
"""
pass
#function which modifies the given list such that all zeros are
pushed at the end
def move_zeros(lst):
#pointer which points to a location at which we will place a
non-zero element
i=0
#iterate on list
for j in range(len(lst)):
#if current element is non-zero then,
if lst[j]!=0:
#place this at ith position and move i by 1
lst[i]=lst[j]
i+=1
#now for the positions left in the list
while i<len(lst):
#place 0 here
lst[i]=0
i+=1
#test case 1
lst = [1, 0, 2, 3]
print("Before: ",lst)
move_zeros(lst)
print("After: ",lst)
#test case 2
lst = [1, 2, 0, 4, 3, 0, 5, 0]
print("Before: ",lst)
move_zeros(lst)
print("After: ",lst)
Before: [1, 0, 2, 3] After: [1, 2, 3, 0]
Before: [1, 2, 0, 4, 3, 0, 5, 0] After: [1, 2, 4, 3, 5, 0, 0, 0]
CODE and OUTPUT
So if you still have any doubt regarding this solution please feel free to ask it in the comment section below and if it is helpful then please upvote this solution, THANK YOU.