Push All Zeros To One Side Of The List
Hello I'm trying to push all zeros in a list to one side without altering the rest of it: [0,2,0,0,9] -> [0,0,0,2,9] [3,4,0,1,0] -> [0,0,3,4,1] My solution: def getNonZeros(
Solution 1:
Since Python sorts are intrinsically stable, you could simple do this
>>> sorted([0,2,0,0,9], key=lambda x: x != 0)
[0, 0, 0, 2, 9]
>>> sorted([3,4,0,1,0], key=lambda x: x != 0)
[0, 0, 3, 4, 1]
Solution 2:
l=[3,4,0,1,0]
new_l = [x for x in l if x!=0]+[0 for y in range(l.count(0))]
[3, 4, 1, 0, 0]
The timing:
In [23]: %timeit [x for x in l if x!=0]+[0 for y in range(l.count(0))]
1000000 loops, best of 3: 752 ns per loop
In [24]: %timeit sorted([3,4,0,1,0], key=lambda x: x != 0)
1000000 loops, best of 3: 1.41 ยตs per loop
Or:
In [25]: %timeit [x for x in l if x != 0] + [0]* l.count(0)
1000000 loops, best of 3: 582 ns per loop
Solution 3:
Just sort the list with a custom key:
In [1]: L = [3, 4, 0, 1, 0]
In [2]: L.sort(key=lambda x: -1 if x == 0 else 1)
In [3]: L
Out[3]: [0, 0, 3, 4, 1]
Note:
- Sorting is guaranteed to be stable, so all the numbers relative order is retained
- Sorting uses tim-sort which is O(n) when the input is almost already sorted, and this is the case (remember that only the keys are compared, which means that the only non-ordered points are when you have a 0 followed by a different number or the opposite).
Post a Comment for "Push All Zeros To One Side Of The List"