piggy
piggy

Reputation: 115

How to check if a variable is in specific range

I have a list of lists that looks like this:

 mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

What I am trying to do is to take a number provided by the user and then check if the number provided is equal or in a range of +0.6 compared to the second element of each sublist. In other words I want to do the following: if user input is 3.4 then I want to check based on the example provided of list of lists these two numbers: 3.4207362518089726 and 2.9687393162393163 and if these numbers are in range of +0.6 from the input, then to save the whole sublist in another list.

So, user_input = 3.4, mylists[0][1] = 3.4207362518089726, mylists[1][1] = 2.9687393162393163 and I want to place in a new list each sublist that has 3.4 and above, till 4.0 (due to range of + 0.6)

What I thought was this:

for i in range(0, len(mylists)):
        if mylists[i][1] >= user_input + 0.6:
             new_list.append(mylists[i])

But of course this did not work.

Upvotes: 0

Views: 365

Answers (3)

Raburgos
Raburgos

Reputation: 1

You can use this:

import re

mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

user_input = 3.4

st = str(user_input) #transform input from user to string

denom = '1'+len(st.split('.')[-1])*'0' #get how much decimals st have and create denominator to the decimal part

decimal_part = 1- int(st.split('.')[-1])/int(denom) #create decimal numbers  to reach upper bound

new_list = []

for i in range(0, len(mylists)):
    if user_input <= mylists[i][1] <= user_input + decimal_part:
         new_list.append(mylists[i])

Another way is:

import numpy as np

mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

user_input = 3.4

new_list = []

for i in range(0, len(mylists)):
    if user_input <= mylists[i][1] <= np.ceil(user_input):
         new_list.append(mylists[i])

Upvotes: 0

CtrlMj
CtrlMj

Reputation: 119

Are you getting an error or just an unexpected output?

perhaps you can try:

new_list = list(filter(lambda x: user_input<= x[1] <= user_input + 0.6 , mylists))

Upvotes: 1

Sam
Sam

Reputation: 1415

Your conditional is just written incorrectly - it is choosing sublists whose 2nd element is
>= user_input + 0.6 (which evaluates to >= 4.0, but you want the 2nd element to be between 3.4 and 4.0. So I believe all you need to do is change it like this:

for i in range(0, len(mylists)):
    if user_input <= mylists[i][1] <= user_input + 0.6:
        new_list.append(mylists[i])

Hope that helps, happy coding!

Upvotes: 1

Related Questions