From e0b8fdc9c6fb76e7a8194b57595677bd9ddab877 Mon Sep 17 00:00:00 2001 From: james Date: Fri, 7 Nov 2025 14:33:23 +0100 Subject: [PATCH] Improve move_zeros for efficiency and readability --- algorithms/arrays/move_zeros.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/algorithms/arrays/move_zeros.py b/algorithms/arrays/move_zeros.py index 606afbfd5..deea12e92 100644 --- a/algorithms/arrays/move_zeros.py +++ b/algorithms/arrays/move_zeros.py @@ -7,20 +7,20 @@ The time complexity of the below algorithm is O(n). """ - -# False == 0 is True def move_zeros(array): result = [] zeros = 0 for i in array: - if i == 0 and type(i) != bool: # not using `not i` to avoid `False`, `[]`, etc. + # Check for numeric zeros but exclude boolean False + # False and other falsy values (like [], '') are NOT treated as zeros. + if i == 0 and not isinstance(i, bool): zeros += 1 else: result.append(i) + + # Append zeros to the end without allocating another temporary list + for _ in range(zeros): + result.append(0) - result.extend([0] * zeros) return result - - -print(move_zeros([False, 1, 0, 1, 2, 0, 1, 3, "a"])) \ No newline at end of file