Home > Back-end >  Python list - finding the index of the element in the triplet that lies between other two elements
Python list - finding the index of the element in the triplet that lies between other two elements

Time:09-21

This is my code:

lst = []
 
for i in range(0, 3):
    ele = int(input("Enter elements of the list: "))
 
    lst.append(ele) 

for x in lst:
    if ((x > lst[0] or x > lst[1] or x > lst[2]) and (x < lst [0] or x < lst[1] or x < lst[2])): 
        print(x)
          
    

It works fine, printing the element that lies between other two elements (is greater than the less and less than the greater), but I need the index of that element. I tried

lst = []
 
for i in range(0, 3):
    ele = int(input("Enter elements of the list: "))
 
    lst.append(ele) 

for x in lst:
    if ((x > lst[0] or x > lst[1] or x > lst[2]) and (x < lst [0] or x < lst[1] or x < lst[2])): 
        print lst.index(x)

But I got error that there is no index of int value.

If someone knows how I can solve this, I would appreciate that. Also if there is a more elegant solution, be free to post it.

CodePudding user response:

A simple and concise solution is to combine enumerate and sorted using the second element of enumerate's output to sort:

lst = [0,2,1]
sorted(enumerate(lst), key=lambda x: x[1])[1][0]
#                                          ↑position that is searched

output: 1

Advantage, this works even if there are repeated values. For example [0,0,0] -> 1

From this, it is easy to generalize to any length. For instance to take the middle element of 5 values:

lst = [0,2,4,1,3]
sorted(enumerate(lst), key=lambda x: x[1])[3][0]

output: 4

@don't talk just code pointed to the alternative lst.index(sorted(lst)[1]) (where 1 is the position that is wanted, here the middle element for a list of 3)

CodePudding user response:

Use the min and max functions.

You've got your code set up to do a complicated comparison for each element, when there's a much more straight-forward way to do it, using Python's built-in min() and max() functions.

Also, you should use try and except for sanitizing user input.

lst = []
 
for i in range(0, 3):
    lst.append("placeholder")
    while isinstance(lst[i], int) is False:
      try:
        ele = int(input("Enter elements of the list: "))
      except:
        print("Type an integer")
      else:
        lst[i] = ele 

minimum = min(lst)
maximum = max(lst)

for x in enumerate(lst):
  if minimum < x[1] < maximum: 
    print(x)

CodePudding user response:

If I were you, I'd try:

lst = []
 
for i in range(0, 3):
    ele = int(input("Enter elements of the list: "))
 
    lst.append(ele) 

for i, x in enumerate(lst):  # changed to enumerate
    if ((x > lst[0] or x > lst[1] or x > lst[2]) and (x < lst [0] or x < lst[1] or x < lst[2])): 
    print(i, x)

Now the code prints the index of the element and its value.

  • Related