-1

my first list of set:

set1 = [
    {'read', 'execute', 'helloworld.exe'}, 
     {'read', 'pinglog', 'write'}, 
     {'read', 'nya'}, 
     {'read', 'execute', 'write', 'goodluck'}
]

now I am looking if these different sets below are in the first list of sets.

final = [
    {'read', 'nya'}, 
    {'helloworld.exe', 'write'},
    {'execute', 'nya'}, 
    {'read', 'pinglog'}, 
    {'write', 'pinglog'}
]

the expected outcome is

OK
Access denied
Access denied
OK
OK
OK

This is my code, I know not much, but my head is already aching for I am trying to do this for two days:

for j in range(len(final)):
    for i in range(len(set1)):
        if final[j] == set1[i]:
            print("OK")

    print("Access denied")
1
  • it should print OK if the a combination in "final" is in the "set1".
    – Rhai
    Commented Oct 21, 2018 at 16:26

2 Answers 2

0

You appear to be testing if your sets are a subset; you can do so with the <= operator on the sets:

>>> final[0], set1[2]  # same
({'nya', 'read'}, {'nya', 'read'})
>>> final[0] <= set1[2]
True
>>> final[3], set1[1]  # subset
({'pinglog', 'read'}, {'write', 'pinglog', 'read'})
>>> final[3] <= set1[1]
True
>>> final[4], set1[1]  # subset
({'write', 'pinglog'}, {'write', 'pinglog', 'read'})
>>> final[4] <= set1[1]
True

Use the any() function and a generator expression to test a given set against all sets in set1:

for request in final:    
    if any(request <= s for s in set1):
        print("OK")
    else:
        print("Access denied")

Demo:

>>> for request in final:
...     if any(request <= s for s in set1):
...         print("OK")
...     else:
...         print("Access denied")
...
OK
Access denied
Access denied
OK
OK
0

We can use a generator expression to check if any x is subset of any set in set1, if so we print OK else Access Denied

for i in ('OK' if any(x <= y for y in set1) else 'Access Denied' for x in final):
    print(i)
OK
Access Denied
Access Denied
OK
OK

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.