""" ------------------------------------------------------- for and while comparison ------------------------------------------------------- Author: David Brown ID: 123456789 Email: dbrown@wlu.ca __updated__ = "2023-06-11" ------------------------------------------------------- """ # Constants SEP = "-" * 60 def wrong_for(values, key): """ Linear search for first occurrence of key in values. ERROR: may return -1 inappropriately. """ for i in range(len(values)): if values[i] == key: index = i else: index = -1 return index def last_for(values, key): """ Linear search for first occurrence of key in values. ERROR: may return last index if key appears more than once. """ index = -1 for i in range(len(values)): if values[i] == key: index = i return index def inefficient_for(values, key): """ Linear search for first occurrence of key in values. INEFFICIENT: loops through all of values even if key already found. """ index = -1 for i in range(len(values)): if index == -1 and values[i] == key: index = i return index def break_for(values, key): """ Linear search for first occurrence of key in values. LIES: for loop claims to visit all of values, break short circuits that. """ index = -1 for i in range(len(values)): if values[i] == key: index = i break return index def while_search(values, key): """ Linear search for first occurrence of key in values. Correct, efficient, truthful. Minimizes work done in body of loop. """ i = 0 while i < len(values) and values[i] != key: i += 1 if i < len(values): index = i else: index = -1 return index # for testing if __name__ == "__main__": print(SEP) print("Testing wrong_for") values = [1, 2, 3, 4, 5] key = 5 index = wrong_for(values, key) print(f"wrong_for({values}, {key}) -> {index}") values = [1, 2, 3, 4, 5] key = 3 index = wrong_for(values, key) print(f"wrong_for({values}, {key}) -> {index}") print(SEP) print("Testing last_for") values = [1, 2, 3, 4, 5] key = 3 index = last_for(values, key) print(f"last_for({values}, {key}) -> {index}") values = values * 2 key = 3 index = last_for(values, key) print(f"last_for({values}, {key}) -> {index}") print(SEP) print("Testing inefficient_for") values = [1, 2, 3, 4, 5] key = 3 index = inefficient_for(values, key) print(f"inefficient_for({values}, {key}) -> {index}") print(SEP) print("Testing while_search") values = [1, 2, 3, 4, 5] key = 3 index = while_search(values, key) print(f"while_search({values}, {key}) -> {index}") print(SEP) print("Done")