This notebook was prepared by Donne Martin. Source and license info is on GitHub.
* None -> TypeError * [0, 1, 0, 3, 12] -> [1, 3, 12, 0, 0] * [1, 0] -> [1, 0] * [0, 1] -> [1, 0] * [0] -> [0] * [1] -> [1] * [1, 1] -> [1, 1]
| [0, 1, 0, 3, 12] ^ | [0, 1, 0, 3, 12] ^ | [1, 1, 0, 3, 12] ^ | [1, 1, 0, 3, 12] ^ | [1, 1, 0, 3, 12] ^ | [1, 3, 0, 3, 12] ^ | [1, 3, 0, 3, 12] ^ | [1, 3, 12, 3, 12] ^ Fill right with zeroes: [1, 3, 12, 3, 12] ^ [1, 3, 12, 0, 12] ^ [1, 3, 12, 0, 0] ^
Complexity:
class Solution(object):
def move_zeroes(self, nums):
if nums is None:
raise TypeError('nums cannot be None')
pos = 0
for num in nums:
if num != 0:
nums[pos] = num
pos += 1
if pos < len(nums):
nums[pos:] = [0] * (len(nums) - pos)
%%writefile test_move_zeroes.py
import unittest
class TestMoveZeroes(unittest.TestCase):
def test_move_zeroes(self):
solution = Solution()
self.assertRaises(TypeError, solution.move_zeroes, None)
array = [0, 1, 0, 3, 12]
solution.move_zeroes(array)
self.assertEqual(array, [1, 3, 12, 0, 0])
array = [1, 0]
solution.move_zeroes(array)
self.assertEqual(array, [1, 0])
array = [0, 1]
solution.move_zeroes(array)
self.assertEqual(array, [1, 0])
array = [0]
solution.move_zeroes(array)
self.assertEqual(array, [0])
array = [1]
solution.move_zeroes(array)
self.assertEqual(array, [1])
array = [1, 1]
solution.move_zeroes(array)
self.assertEqual(array, [1, 1])
print('Success: test_move_zeroes')
def main():
test = TestMoveZeroes()
test.test_move_zeroes()
if __name__ == '__main__':
main()
Overwriting test_move_zeroes.py
%run -i test_move_zeroes.py
Success: test_move_zeroes