0

Was having fun with this task on code wars where on a given list as an input my function should find all of the zeroes and put them at the end of a given list maintaining the other numbers in the same order for example: a = [1, 2, 0, 1, 0, 1] function should return a = [1, 2, 1, 1, 0, 0]

I wrote a code which in my VS code does the job but for some reason cant pass the initial tests (4/5).

The thing is on failed test where my function should return some values, IT ACTUALLY DOES, in my compiler but cant pass test??? I'm really confused. I did not want to look for solutions online...

Here is my code:

def zerotoanend(a:list):
    b = []
    for i in a:
        if i==0:
            b.append(0)
            a.remove(i)
    for zero in b:
        a.append(zero)
    return a
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    Can you share the *failed* test here? We cannot see what's happening on that one - unless you share more info. – Daniel Hao Feb 19 '23 at 02:14

1 Answers1

-1

It is generally not a good idea to modify a list while iterating over it, as you can skip elements. Instead, you could count the number of zeros first, use a list comprehension to get all the non-zero elements, then add the required number of zeros to the end.

zeros = a.count(0)
return [x for x in a if x != 0] + [0] * zeros
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Thank you! Well, initially it was my core idea, to count and separate all the zeros in b list and then that number or total zeros add at the end of 'a' list. – Miloš Grujić Feb 19 '23 at 06:18