183k views
2 votes
Python Exercise:

1. Modify your program to search in several collections based upon input
1. A list of strings: ['A', 'B', 'C', 'D', 'E', … , 'Z']
2. A list of ints: [1, 2, 3, 4, 5, 6, …, 100]
3. A list of floats: [1.2, 2.3, 3.4, 4.5, 5.6]
2. Prompt the user for which list to search and for a value to search for
3. Print out the result including the list searched and the index of the found value.
4. If the value is not found, print an appropriate response
Again, make sure you test the input and catch possible errors ensuring the program runs regardless of input
Example Input/Output
>>> Which list do you want to search?Press 1 for strings, 2 for ints, 3 for floats: 1
>>> Enter the value to search for: f
>>> Found it in string list at index 5 using a linear search and it took 5 steps
>>> Found it at index 75 using a binary search and I took 2 steps

User Maxpill
by
8.3k points

1 Answer

5 votes

Final answer:

The Python exercise requires the creation of a program that can search through three different types of collections based on user input, report the index of a found value, and handle errors for robustness.

Step-by-step explanation:

To complete the Python exercise described, we need to write a program that can search through three different collections: a list of strings containing the uppercase letters of the alphabet, a list of integers from 1 to 100, and a list of floating-point numbers. First, the program will prompt the user to select which list to search. Then, the user will be asked to input the value they wish to find. Depending on the user's choice of list, the search will be performed, and the program will print the result, including the list where the search occurred and the index of the found value. If the value is not found, an appropriate message should be displayed. To ensure robustness, the program should handle errors such as invalid input.

Here is a simplified example of how the code might be structured to handle the user's requests robustly:

Python Code Example:
def search_collection(collection, target):
for index, value in enumerate(collection):
if value == target:
return index
return -1The code defines a function search_collection() that takes a collection and a target value, searches for the target, and returns the index or -1 if not found.

User Falico
by
7.3k points