My assignment is to get a list from the user and print out the second largest item in said list.
The user should be able to enter strings or integers.
I'm having issues comparing the two as I get errors when using max().
Here is my code thus far:
list_input_amount = int(input('How many items are in your list?: '))
for amount in range(list_input_amount):
list_input = input('Please enter your list item: ')
if list_input.isnumeric():
random_list.append(int(list_input))
else:
random_list.append(list_input)
print(random_list)
def second_largest():
maximum_list = set(random_list)
maximum_list.remove(max(maximum_list))
print(max(maximum_list))
second_largest()
Thanks in advance for the help
You can a dict {}
to store the value that'll be used to compare, and then sort and take the second one.
Here is the code, a bit more generic to get the nth
element :
# List comprehension
def nth_largest(values: {}, nth=0):
return [k for k,v in sorted(values.items(), key=lambda kv:kv[1], reverse=True)][nth][0]
# Two steps
def nth_largest(values: {}, nth=0):
sorted_x = sorted(values.items(), key=lambda kv: kv[1], reverse=True)
return list(sorted_x)[nth][0]
if __name__ == '__main__':
list_input_amount = int(input('How many items are in your list?: '))
dico_values = {}
for amount in range(list_input_amount):
list_input = input('Please enter your list item: ')
if list_input.isnumeric():
dico_values[int(list_input)] = int(list_input)
else:
dico_values[list_input] = len(list_input)
print(nth_largest(dico_values, 1))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments