5

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"
2
  • 1
    Could there be a list like d = [1,1,2], and if so, would you consider it a "subset" of a or not? Commented Mar 19, 2014 at 8:34
  • Tim, you are right.. You have pointed out the loophole on my code to validate a subset. If I am not mistaken, in math, the d is not a subset of a. But for my script, I will still consider it as the "subset" of a. As it won't affect my expected result. Thanks for your reminder :) Commented Mar 22, 2014 at 13:51

3 Answers 3

3

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, this solve my problem :D Although other answers are useful too, but I am limited to this if-else structure. Thanks everyone :D
2

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.