Second Largest

The questions below are due on Thursday July 01, 2021; 11:00:00 AM.
 
You are not logged in.

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.
Part 1

Ben Bitdiddle has written the following piece of code, designed to find and return the largest number in a list of arbitrary numbers (ints and/or floats):

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)

The goal is that this function should always return the largest number in 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 ints or floats. 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

Part 2

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)!

  No file selected

Please upload your code again here. This question will be manually graded for good code style. Remember to use succinct, descriptive variable names and comments (such as docstrings, which were mentioned in Batching) to explain confusing lines. This function is expected to be less than 40 lines.
 No file selected

Next Exercise: Survey

Back to exercises