Reputation: 499
I am writing a script that, if an array's elements are the subset of the main array, then it print PASS, otherwise, it print FAIL instead.
What should I add to my if-else statement below to make it works?
a = [1,2,3,4,5]
b = [1,2]
c = [1,9]
# The Passing Scenario
if (i in a for i in b):
print "PASS"
else:
print "FAIL"
# The Failing Scenario
if (i in a for i in c):
print "PASS"
else:
print "FAIL"
Upvotes: 5
Views: 245
Reputation: 239443
This can be done with the set operations like this
a = [1,2,3,4,5]
b, c = [1,2],[1,9]
print set(b) <= set(a)
# True
print set(c) <= set(a)
# False
Upvotes: 2
Reputation: 336078
With set
s, it's easy:
>>> a = [1,2,3,4,5]
>>> b = [1,2]
>>> c = [1,9]
>>> set(b).issubset(set(a))
True
>>> set(c).issubset(set(a))
False
Upvotes: 2
Reputation: 9874
Use all
.
# the passing scenario
if all(i in a for i in b):
print 'PASS'
else:
print 'FAIL'
# the failing scenario
if all(i in a for i in c):
print 'PASS'
else:
print 'FAIL'
Upvotes: 3