In: Computer Science
Problem 3: Minimum
In this problem, we will write a function to find the smallest element of a list. We are, in a sense, reinventing the wheel since the min() function already performs this exact task. However, the purpose of this exercise is to have you think through the logic of how such a function would be implemented from scratch.
Define a function named minimum(). The function should accept a single parameter named x, which is expected to be a list of elements of the same type. The function should return the smallest element of x. The function should work on lists of integers, floats, and strings. In each case, the "smallest" element is defined as the one with the lowest ranking with respect to the < comparison operator. For strings, this should yield the earliest string when ordered alphabetically.
The function should not print anything. It should not create any new lists, and should involve only one loop.
Furthermore, this function should not make use of ANY built-in Python functions other than range() and len(). No credit will be awarded for solutions that use the min() function.
We will now test the minimum() function. Create a new code cell to perform the steps below. Create three lists as shown below:
list1 = [9.8, 7.4, 5.6, 4.8, 4.8, 5.3, 4.1, 9.6, 5.4]
list2 = [3.4, 7.6, 8.7, 7.5, 9.8, 7.5, 6.7, 8.7, 8.4]
list3 = ['St. Louis', 'Kansas City', 'Chicago', 'Little Rock', 'Omaha']
Use the minimum() function to calculate the minimum of each of these lists, printing the results
CODE -
def minimum(x):
# Initializing the value of minm(smallest value of the list) with
the first element of the list
minm = x[0]
# Iterating over the list starting from the 2nd element
for i in range(1, len(x)):
# Assigning the value of the currently processed element to minm if
it is less than minm
if x[i]<minm:
minm = x[i]
# Returning the value of minm(smallest value of the list)
return minm
SCREENSHOT -
If you have any doubt regarding the solution, then do
comment.
Do upvote.