forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmove_zeros.py
More file actions
44 lines (31 loc) · 954 Bytes
/
move_zeros.py
File metadata and controls
44 lines (31 loc) · 954 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
Move Zeros
Move all zeros in an array to the end while preserving the relative order
of the non-zero (and non-integer-zero) elements.
Reference: https://leetcode.com/problems/move-zeroes/
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
from typing import Any
def move_zeros(array: list[Any]) -> list[Any]:
"""Move all integer zeros to the end, preserving order of other elements.
Boolean False is not treated as zero.
Args:
array: Input list with mixed types.
Returns:
New list with all integer 0s moved to the end.
Examples:
>>> move_zeros([False, 1, 0, 1, 2, 0, 1, 3, "a"])
[False, 1, 1, 2, 1, 3, 'a', 0, 0]
"""
result = []
zeros = 0
for element in array:
if element == 0 and type(element) is not bool:
zeros += 1
else:
result.append(element)
result.extend([0] * zeros)
return result