Python's 3rd largest method of calculation

Asked 2 years ago, Updated 2 years ago, 36 views

def find_3rd max(L):
    L=[]
    m=L[0]
    for i in range(len(L)):
        if m>i:
            m=i
        L.pop(0)
        L.pop(1)
    return L[0] 

I'm going to take the integers into the list L and compare them one by one, sort the largest value to the left, delete the previous two big values, and print out the third big value, shouldn't I do this? Why isn't it coming out?

python list

2022-09-21 15:59

1 Answers

Q. Why isn't it coming out?

A. I'm sorry to say this, but if you read the code again, it's a code that doesn't work from beginning to end.

def find_3rd max(L): # Shouldn't there be a space in the function name?
    L=[] # Why do you reset the function to an empty array when the first factor of the function has crossed over to L?
    m=L[0] #L is an empty array, so what is L[0] to assign to m?
    For i in range (len(L): # It would be like for i in 0 after all... So can this loop be executed at least once?
        if m>i: # Will this operation work? What is m here?
            m=i # Is the intention to make m smaller than the existing m?
        L.pop(0) # Does this pop have to happen every time in the for loop?
        L.pop(1) # Why are you poping again?
    return L[0] # I think it'll be more interesting to see something come out from here.

Q. Can't we compare one by one and arrange the largest value to the left, then delete the previous two large values and print out the third large value?

A. I don't know. I think you're talking too much Do you need to implement a sorting algorithm? To be honest, if you get what you want, it's kind of simple.

def getThirdBiggestInt(L) :
    L.sort()
    return L[0] if len(L) < 3 else L[-3]

X = [19,227,-3,9987,386,20]
print(getThirdBiggestInt(X)) # 227

Y = [3,2]
print(getThirdBiggestInt(Y)) #2 (*Return the smallest number because the number of elements in the list is less than 3)


2022-09-21 15:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.