Home > front end >  Search one smaller and one bigger number then serach term?
Search one smaller and one bigger number then serach term?

Time:05-31

I have a list in the python and I want to find out the search term with conditions one smaller and one bigger number the search term.

list =  [2, 3, 5, 7, 9, 12, 19, 22, 34]
search_term = 10

I want to get one smaller and one bigger term next to the search term from the list.

The expected result should be

output = [7, 9]

CodePudding user response:

Edit for [7, 9]

Search up until you are >= search_term, then print last 2 values:

# Don't use class names (list) as variables
lst = [2, 3, 5, 7, 9, 12, 19, 22, 34]
search_term = 10

# Sort list for iterating. lst is now sorted
lst.sort()
index = 0

# Get index of values. Stop when item >= search_term
for i, item in enumerate(lst[1:]):
    if item >= search_term:
        index = i
        break

output = [lst[index-1], lst[index]]
>>> output
[7, 9]

This was for printing value before and after search_term

There was no output, and this was a guess at what OP wanted

You can iterate over your lst and check for > and < search_term:

  • This works for non-empty lists
# Don't use class names (list) as variables
lst = [2, 3, 5, 7, 9, 12, 19, 22, 34]
search_term = 10

# Sort
lst.sort()
last = lst[0]
index = 0

# Get item before
for i, item in enumerate(lst[1:]):
    if item < search_term:
        last = item
        index = i
    else:
        break

print(f'Before = {last}')

# Get item after
try:
    for item in lst[index 1:]:
        if item >= search_term:
            last = item
            break
except IndexError:
    pass
    # You don't have any values after the before value

print(f'After  = {last}')
Before = 9
After  = 12

An exception may be the case of:

>>> lst = [1, 10]
>>> search_term = 10

Which prints

Before = 1
After  = 10

CodePudding user response:

Code:

l =  [2, 3, 5, 7, 9, 12, 19, 22, 34]
search_term = 10    
 

tmp = [max([t for t in l if t <= search_term])] # smaller than search
tmp.append(min([t for t in l if t >= search_term])) #bigger than search

print("nearest smaller :",tmp[0]) 
print("nearest bigger :",tmp[1])

Output:

nearest smaller : 9
nearest bigger : 12
  • Related