user3431399
user3431399

Reputation: 499

Simple if-else statement in Python

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

Answers (3)

thefourtheye
thefourtheye

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

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

With sets, 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

Jayanth Koushik
Jayanth Koushik

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

Related Questions