-5

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
Eric Darchis
  • 24,537
  • 4
  • 28
  • 49
  • 2
    Please post your code and output instead of images – Dhaval Taunk Jun 13 '20 at 08:51
  • 1
    Please consult https://stackoverflow.com/help/how-to-ask for tips on how to ask a question here. Also, please search SO before posting a question https://stackoverflow.com/a/16225736/503835 – eNc Jun 13 '20 at 09:13
  • 2nd while loop change the if to `a[i] < secondbig` and there is no need of else you can use single `if` condition `if a[i] != big and a[i] < secondbig` – deadshot Jun 13 '20 at 09:22

1 Answers1

1

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.
Saaheer Purav
  • 39
  • 3
  • 5