Mercurial > louis > peeves
view arrays/pack_values_at_beginning/solution.py @ 0:20fea762903e
Import some exercises and solutions
author | Louis Opter <kalessin@kalessin.fr> |
---|---|
date | Sat, 29 Jun 2013 19:30:31 -0700 |
parents | |
children |
line wrap: on
line source
#!/usr/bin/env python # Given an array of integer and a specific integer value (e.g: 4) you need to # move all the integer with that value (in the array) at the beginning of the # array. The order of the other elements must not change. import random def pack(array, n): src = dest = len(array) - 1 while src >= 0: while src >= 0 and array[src] == n: src -= 1 if src >= 0 and src != dest: array[dest] = array[src] src -= 1 dest -= 1 while dest != -1: array[dest] = n dest -= 1 array = [random.choice(range(10)) for i in range(15)] n = random.choice(range(10)) print("array = {0}, n = {1}".format(array, n)) pack(array, n) print("array = {0}".format(array)) print("****") array = [7, 9, 0, 8, 2, 3, 9, 9, 9, 2, 5, 6, 6, 0, 1] n = 9 print("array = {0}, n = {1}".format(array, n)) pack(array, n) print("array = {0}".format(array))