I have this code, which will sort the inputs, but the only way it works is by the inputs being sorted before they are entered into the list. I want to re write the code to take any list and output the word or number, whichever happens to be second largest.
def secound_largest(values: {}):
sorted_values = sorted(values.items(), key=lambda kv: kv[1], reverse=True)
second_maximum = list(sorted_values)[1][0]
print(str(second_maximum)+ 'is the second largest item on the list')
if __name__ == '__main__':
list_input_amount = int(input('How many items are in your list? '))
dictonary_values = {}
for amount in range(list_input_amount):
list_input = input('Please enter your list item: ')
if list_input.isnumeric():
dictonary_values[int(list_input)] = int(list_input)
else:
dictonary_values[list_input] = len(list_input)
secound_largest(dictonary_values)
The following code will do what you want:
def argmax(subscriptable):
_max = subscriptable[0]
_max_inv = 0
for idx in range(1, len(subscriptable)):
elem = subscriptable[idx]
if elem > _max:
_max = elem
_max_inv = idx
return _max_inv
def second_large_arg(subscriptable):
big1 = subscriptable[0]
big2 = subscriptable[1]
big1_inv = 0
big2_inv = 1
if big1 < subscriptable[1]:
big1 = subscriptable[1]
big2 = subscriptable[0]
big1_inv = 1
big2_inv = 0
for idx in range(2, len(subscriptable)):
elem = subscriptable[idx]
if elem > big1:
big2_inv = big1_inv
big1 = elem
big1_inv = idx
elif elem > big2:
big2 = elem
big2_inv = idx
return big2_inv
d = {
0:23,
1:83,
2:999999999999999999999999999999,
3:87,
4:91,
5:32111111,
6:21
}
print(argmax(d)) # prints 2
print(second_large_arg(d)) # prints 5
L = {
0:"apple",
1:1,
2:"SUBDERMATOGLYPHIC",
3:"banana",
4:99999999999999,
5:2
}
L = [len(x) if hasattr(x, "__len__") else x for x in L.values()]
print(L)
print(argmax(L)) # prints 4
print(second_large_arg(L)) # prints 2
list2= [] list= [3, 5, 'python', 2, -1, 7] for i in range(len(list)): try: item=[len(list[i]),list.index(list[i])] list2.append(item) except TypeError: item= [list[i],list.index(list[i])] list2.append(item) list2.sort(key=lambda x:x[0],reverse=True) print(list[list2[1][1]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.