Reputation: 1302
I'm setting up a new script where I need to check if a list has all the elements between 2 numbers, to check the continuity of this list.
At the moment, I've tried to add the minimum value and the maximum value, and I compare it with the number of the elements on the list.
if max+min > 2*count:
continuity = 'no'
else:
continuity = 'yes'
Update
This is not a duplicate question. I'll explain with further information my question. I want to check If a study is realized on every X-value and Y-value.
For example, with 4 points, I have:
X=[1, 1, 2, 2]
Y=[1, 1, 2, 2]
Referring to X1=(1,1)
, X2=(1,2)
, ... and so on.
At the moment, I've tried with 2 dict:
countY = dict([(k, Y.count(k)) for k in set(Y)])
countX = dict([(k, X.count(k)) for k in set(X)])
I compare it with the max and min value, but I just search a function (if it exists) which allows me to do this, using less lines.
Upvotes: 0
Views: 1558
Reputation: 14734
You could do this, which handles duplicate elements:
assert len(set(my_list) - set(range(min_, max_))) == 0
like
my_list = [2, 2, 3, 1, 4]
min_ = 1
max_ = 5
ref = set(range(min_, max_)) # all the elements you want, in a set
assert len(set(my_list) - ref) == 0
# or
assert all(x in ref for x in my_list)
# or
assert sorted(my_list) == sorted(ref) # fails if there are repeating element in my_list
test:
import random
def f(l, min_, max_):
assert sorted(l) == list(range(min_, max_))
def g(l, min_, max_):
s = set(l)
ref = set(range(min_, max_))
assert len(s - ref) == 0
def h(l, min_, max_):
s = set(l)
ref = set(range(min_, max_))
assert all(x in ref for x in s)
min_ = -100
max_ = 100
l = list(range(min_, max_))
random.shuffle(l)
%timeit f(l, min_, max_)
#28.2 µs ± 6.1 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit g(l, min_, max_)
#12.5 µs ± 1.52 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit h(l, min_, max_)
#28.8 µs ± 12 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Upvotes: 3