# # Compare two implementations of a function that count how many # times a particular value occurs within a list. # # # Count the number of times that a particular value appears in a list. # # Parameters: # data: The list of values to evaluate # what: The value that we are looking for # # Return: The number of times what occurs in data # def count_for(data, what): count = 0 for item in data: if item == what: count = count + 1 return count # # Count the number of times that a particular value appears in a list. # # Parameters: # data: The list of values to evaluate # what: The value that we are looking for # # Return: The number of times what occurs in data # def count_while(data, what): count = 0 while len(data) > 0: item = data.pop() if item == what: count = count + 1 return count # # Demonstrate that changes made inside count_while also impact the # list in the main program. # def main(): test_values = [1, 2, 3, 4, 5, 4, 3, 2, 3, 4, 2, 1, 1, 1, 2, 3] print("Using count_for, 1 occurrs in test_values", count_for(test_values, 1), "times") print("Now test_values is", test_values) print("Using count_while, 1 occurrs in test_values", count_while(test_values, 1), "times") print("Now test_values is", test_values) print("Using count_for, 1 occurrs in test_values", count_for(test_values, 1), "times") print("Now test_values is", test_values) main()