I need to write a function that takes a list as a parameter and find the second highest value in the list. Return that value. If there is only one value in the list, return that value. If the list is empty, return 0.
To create the list, I prompt the user for numbers until the user enters a sentinel value of -1. Then I prompt the user for a beginning location (loc) and a length (len). I would extract a list slice that begins at index loc and has length len and then use my function to find the second highest value in that list slice.
Here's the code I have so far:
userList = []
def main():
inputList = int(input("Enter a number >= 0. Enter -1 to end input: "))
while inputList != -1:
userList.append(inputList)
inputList = eval(input("Enter a number >= 0. Enter -1 to end input: "))
return extractList(userList)
def extractList(userList):
loc = int(input("Enter a starting location: "))
length = int(input("Enter a lenghth: "))
selSlice = userList[loc:loc + length]
if len(selSlice) == 1:
return selSlice[0]
if len(selSlice) == 0:
return 0
num = max(selSlice)
occ = userList.count(num)
for i in range(occ):
userList[userList.index(num):userList.index(num)+1] = ''
print("Second highest value in ", selSlice, "is ", max(selSlice))
main()
I'm testing to see if the slice works, but it seems to take the starting index of loc and goes to ending index of len instead of going out the length of len.
Example, if I have a list:
[1, 3, 7, 21, 37, 76, 23, 91, 15, 11, 2, 4]
and my loc
is 3 and my len
is 6, the result should be [21, 37, 76, 23, 91, 15]
. However, I'm not getting this desired result, instead I would get [21, 37, 76]
.
What should my extractList(a)
be? Also, if you could help me with the function to find the second highest value, it'd be great. Thanks for any input!
Edit:
Ok, so I'm on the right track now, thanks to Chris Arena and To Click or Not to Click. (Code has been updated)
However, the code above gives me the second highest value of the whole list, not the sliced list. I'm not sure if all the variables are correct.
If my userList
is [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
and my loc is 6 and length is 4, I get [4, 6, 8, 10]
back, as I should, but the second highest value of the slice is 9, which is the second highest of userList, not the slice.
I tried to change userList
to selSlice
starting from line if len(userList) == 1:
through to the end to see if that made a difference. It did, but the results were questionable (aka wrong). I used the same userList, loc, and length as mentioned in the previous paragraph. I got [4, 6, 8]
back as the slice (wrong) and the second highest value is 8, which is wrong for the slice the program returned but right for my slice that I requested. So I'm not sure what could be wrong here. Any advice?
Edit to Edit:
My latest code shows the correct slice, but the wrong 2nd highest value. I'm getting:
Second highest value in [4, 6, 8, 10] is 10
Not sure what needs fixing =\