Reputation: 13
I have a value to check in the list range
Example:
recipies = int(input("enter:"))
print(recipies)
interval =[]
for i in range(recipies):
x = (input().split())
interval.append(x)
print(interval)
agroup =int(input("enter:"))
print(agroup)
qali = []
for i in range(agroup):
x = (input().split())
qali.append(x)
print(qali)
for cmp in qali:
toa = cmp[1:]
Input:
4
1 4
3 10
2 6
5 8
3
1 5
2 2 6
3 1 10 9
Output:
3
4
2
Here i want to check weather the value of toa available in the interval if available i want to print how many times that value available in the given intervals,same way i want to check values in quali(list)
Upvotes: 0
Views: 3222
Reputation: 107287
You can use following list comprehensions :
>>> f_list=[map(int,i.split(',')) for i in li]
>>> ['yes' if toa in range(i,j) else 'No' for i,j in f_list]
['yes', 'yes']
Fist you need to extract your ranges that it can be done with splitting your strings with ,
and convert to int
with map
function.
Then you can use a list comprehension like following to check the member-ship :
['yes' if toa in range(i,j) else 'No' for i,j in f_list]
But not that range
will contains the start
but not end
if you dont want such things you need to increase your start when you want to create the range :
>>> ['yes' if toa in range(i+1,j) else 'No' for i,j in f_list]
['yes', 'No']
Upvotes: 2
Reputation: 1121416
You'll have to parse each string into a start and stop value (integers):
ranges = ['1,9', '2,10']
for start_stop in ranges:
start, stop = map(int, start_stop.split(','))
if toa in range(start, stop):
print('yes')
Instead of creating a new range()
object you can just use comparison operators:
for start_stop in yourlist:
start, stop = map(int, start_stop.split(','))
if start <= toa < stop:
print('yes')
This'll be faster as you don't need to create an additional range()
object.
You probably want to store those integers instead:
ranges = [[int(i) for i in start_stop.split(',')] for start_stop in ranges]
to not have to parse them each and every time.
If you need to do a lot of these tests, against a large number of intervals, consider using an Interval Tree data structure instead. In an Interval Tree finding matching ranges (intervals) takes O(log N) time, vs. O(N) for the straight search. So for 10000 ranges to test against, it'll only take 100 steps to find all matches, vs 10000 steps using the straight search used above.
Upvotes: 1