Second Largest
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
Ben Bitdiddle has written the following piece of code, designed to
find and return the largest number in a list of arbitrary numbers
(int
s and/or float
s):
def largest_number(input_list):
best_so_far = 0
for i in range(len(x)):
if i > best_so_far:
best_so_far = i
print(best_so_far)
input_list
. We can assume that input_list
always has at least one element in it, and that all of the elements in it are either int
s or float
s. Sadly, there are bugs in the code above exactly as written. Please describe any bugs you can find (there are 4 main bugs, but finding less will still get partial credit).
You don't need to say how fix the bugs and feel free to be very brief. For example, one of the bugs is that "Ben is looping over the indices but he should be looking at the elements of the list".
Formatting Help
In a file on your own machine, write and test a function called
second_largest_number
that takes as input a single list containing 0
or more numbers. If there are 0 or 1 numbers in the given list, your
function should return None
. Otherwise, it should return the
second largest number in the list.
For full credit, your code should not use built-in functions such as max
or sorted
.
You do not need to handle the case where elements in the provided list are not numbers.
For example, running the following code:
print(second_largest_number([]))
print(second_largest_number([2]))
print(second_largest_number([94, 87, 20, 35]))
print(second_largest_number([20, -1, -10]))
print(second_largest_number([8,8,7,6,5]))
should print:
None
None
87
-1
8
Pay particular attention to the last example. It does not print 7
since 8
is both the largest and second largest number.
Start by making a plan and running through some test cases of your own devising on paper. Once you are confident in your plan, implement your function and test using the Python interpreter. When you are ready, submit your file below.
Your code will be graded based on accuracy, as normal, but you will also receive some feedback on style (so check back here after the assignment is due)!
Next Exercise: Survey