简体   繁体   中英

Finding the 2 biggest numbers in a list

I have to find the 2nd biggest number in a list. I wrote the program below that runs properly when the input first encounters the second biggest number. If the input has the biggest number first, the result is that biggest number twice.

#pr no:78
#11/06/2020
# find out the 2nd biggest element in list using list
a=[]
x=int(input("value of x "))
while x!=1000:
    a.append(x)
    x=int(input("value of x "))
n=len(a)
i=0
big=a[0]
while i<n:
    if a[i]>big:
        big=a[i]
    i+=1
print("first big number",big)
i=0
secondbig=a[0]
while i<n:
    if a[i]!=big:
        if a[i]>secondbig:
            secondbig=a[i]
    i+=1
print ("second big number",secondbig)

1st output:

value of x 100
value of x 5000
value of x 200
value of x 1000
first big number 5000
second big number 200

Process finished with exit code 0

if i give the first number is small it shows me the correct answer

2st output:

value of x 5000
value of x 200
value of x 100
value of x 1000
first big number 5000
second big number 5000

Process finished with exit code 0

You can use.sort() for sorting the array in ascending order.

numbers = [7,3,8,1,6,4] #Here, we have to find 7, which is the second biggest number.
numbers.sort() #This arranges the numbers in ascending order.
print(numbers[-2]) #This prints the second last number or largest number in the list.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM