0

The question is simply 'Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.'

Here is the code I wrote:

def move_zeros(lst):
    num_zeros = 0
    for num in lst:
        if num == 0:
            lst.remove(num)
            num_zeros+=1
    i = 1
    while i<=num_zeros:
        lst.append(0)
        i+=1
    return lst

Input: [9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]

Output: [9, 9, 1, 2, 1, 1, 3, 1, 9, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0]

Expected: [9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

drum
  • 5,416
  • 7
  • 57
  • 91
  • Don't remove the zeroes from the list, move the non-zero elements to the front of the list in-place. Then set the last `num_zeros` elements to zero. – AspectOfTheNoob Jan 08 '23 at 21:56

0 Answers0