Python Forum
How to terminate a list of inputs with a set value? SOS
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to terminate a list of inputs with a set value? SOS
#1
I am attempting to make a program in Python 3.7 where you would input integers one after another until you terminate it by entering the value -3. Once you input -3, the program would print the second highest number you've listed.

My current code is:
a=[]
n=int(input("Enter number:"))
  for i in range(1,n+1):
  n=int(input("Enter number:"))
  a.append(n)
    if n == -3:
      break
a.sort()
print("Second largest number is:",a[n-2])
I keep getting the error:
Error:
Traceback (most recent call last): File "main.py", line 9, in <module> print("Second largest number is:",a[n-2]) IndexError: list index out of range
If anyone could help me out it would be greatly appreciated as I am still a beginner with this language.
Reply
#2
Please read https://python-forum.io/misc.php?action=help&hid=25 how to use code tags to format your question.
The error is because the first time your list a[] will have 1 item. So a[n-2] will yield a negative index. This is the error you get.
Reply
#3
I don't see a "while" loop in your code. At least, you need to put "while True:" somewhere. You can use negative indexing to get the second element from the tail of a list. Finally, your solution is of O(n) space complexity (n the number of entered numbers); It would be useful if you try to find O(1) solution as well (i.e. without storing all entered numbers to a list).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  The game should now run and terminate once the board is full, but still can’t identif rango 0 1,429 Jul-22-2021, 03:24 AM
Last Post: rango
  Is there a way to not terminate a running thread in python Contra_Boy 3 1,932 May-05-2020, 09:38 PM
Last Post: SheeppOSU
  Terminate a process when hotkey is pressed 66Gramms 0 2,210 Dec-24-2019, 06:41 PM
Last Post: 66Gramms
  How to terminate the caller fuction through callee? 100k 2 2,101 Nov-27-2019, 06:49 PM
Last Post: jefsummers
  how to terminate all the processes in C py2exe 0 2,050 Aug-02-2018, 04:31 AM
Last Post: py2exe
  lambda-Amazon EC2:Remove instance termination protection if enabled and terminate ins dragan979 0 3,314 Jun-13-2018, 09:48 AM
Last Post: dragan979
  Using Terminating Signal to Terminate Long Threads crcali 1 2,560 Apr-06-2018, 01:26 AM
Last Post: woooee
  Service that waits for another program to terminate hhh 1 2,517 Dec-15-2017, 01:39 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020