patternpythonMajor
Push all zeros to tail of int array
Viewed 0 times
zerosallarraytailpushint
Problem
My script pushes zeros to end of an int array. I'd like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.
def nonzero(a):
''' given an array of ints, push all zeros to the end '''
zeros = [0 for i in range(a.count(0))]
x = [ i for i in a if i != 0]
x.extend(zeros)
return(x)Solution
-
The function does not preserve object identity. Zeros of other types get replaced with an integer:
If the input only ever contains integers, then this isn't a problem, but it's worth remembering that Python has several different types of number.
-
The docstring is not quite right. "push all the zeros to the end" implies that the input array is modified, but that's not true: a new array is created and returned.
-
There's a neat trick for implementing this:
This works because
The function does not preserve object identity. Zeros of other types get replaced with an integer:
>>> nonzero([0, 0.0, 0j])
[0, 0, 0]If the input only ever contains integers, then this isn't a problem, but it's worth remembering that Python has several different types of number.
-
The docstring is not quite right. "push all the zeros to the end" implies that the input array is modified, but that's not true: a new array is created and returned.
-
There's a neat trick for implementing this:
def nonzero(a):
"""Return a copy of the iterable a with all zeros at the end."""
return sorted(a, key=lambda x: x == 0)This works because
False compares less than True, and because Python's sort is guaranteed to be stable: it never changes the relative order of elements with the same sort key.Code Snippets
>>> nonzero([0, 0.0, 0j])
[0, 0, 0]def nonzero(a):
"""Return a copy of the iterable a with all zeros at the end."""
return sorted(a, key=lambda x: x == 0)Context
StackExchange Code Review Q#109483, answer score: 22
Revisions (0)
No revisions yet.