Python Examples
Dave Braunschweig
Arrays
# This program demonstrates array processing, including: # display, total, max, min, parallel arrays, sort, # fixed arrays, dynamic arrays, and multidimensional arrays. import random def display_array(array): for index in range(len(array)): print('array[' + str(index) + '] = ' + str(array[index])) def calculate_sum(array): total = 0 for index in range(len(array)): total += array[index] return total def calculate_maximum(array): maximum = array[0] for index in range(1, len(array)): if maximum < array[index]: maximum = array[index] return maximum def calculate_minimum(array): minimum = array[0] for index in range(1, len(array)): if minimum > array[index]: minimum = array[index] return minimum def demonstrate_parallel_arrays(names, ages): for index in range(len(names)): print(names[index] + ' is ' + str(ages[index]) + ' years old') def demonstrate_fixed_array(): array = [None] * 5 for index in range(len(array)): array[index] = random.randint(0, 100) display_array(array) def demonstrate_dynamic_array(): array = [] for index in range(5): array.append(random.randint(0, 100)) display_array(array) def demonstrate_multidimensional_array(): game = [ ['X', 'O', 'X'], ['O', 'O', 'O'], ['X', 'O', 'X'] ] for row in range (0, 3): for column in range(0, 3): print(game[row][column], end='') if column < 2: print(' | ', end='') print() def main(): names = ['Lisa', 'Michael', 'Ashley', 'Jacob', 'Emily'] ages = [49, 48, 26, 19, 16] display_array(names) display_array(ages) total = calculate_sum(ages) maximum = calculate_maximum(ages) minimum = calculate_minimum(ages) print('total: ' + str(total)) print('maximum: ' + str(maximum)) print('minimum: ' + str(minimum)) demonstrate_parallel_arrays(names, ages) ages.sort() display_array(ages) demonstrate_fixed_array() demonstrate_dynamic_array() demonstrate_multidimensional_array() main()
Output
array[0] = Lisa array[1] = Michael array[2] = Ashley array[3] = Jacob array[4] = Emily array[0] = 49 array[0] = Lisa array[1] = Michael array[2] = Ashley array[3] = Jacob array[4] = Emily array[0] = 49 array[1] = 48 array[2] = 26 array[3] = 19 array[4] = 16 total: 158 maximum: 49 minimum: 16 Lisa is 49 years old Michael is 48 years old Ashley is 26 years old Jacob is 19 years old Emily is 16 years old array[0] = 16 array[1] = 19 array[2] = 26 array[3] = 48 array[4] = 49 array[0] = 18 array[1] = 14 array[2] = 59 array[3] = 99 array[4] = 61 array[0] = 85 array[1] = 4 array[2] = 35 array[3] = 45 array[4] = 93 X | O | X O | O | O X | O | X