6

I have two sets:

a = set(['this', 'is', 'an', 'apple!'])
b = set(['apple', 'orange'])

I want to find if there are any (b) in (a) including substrings. normally I would do:

c = a.intersection(b)

However, in this example it would return an empty set as 'apple' != 'apple!'

Assuming I cannot remove characters from (a) and hopefully without creating loops, is there a way for me to find a match?

Edit: I would like for it to return a match from (b) e.g. I would like to know if 'apple' is in set (a), I do not want it to return 'apple!'

0

3 Answers 3

7

Instead of doing the equality check via ==, you can use in for substring match which also covers equality:

>>> [x for ele in a for x in b if x in ele]
["apple"]
3
  • This is working but it seems to be returning ["apple!"]. How can I make it return ["apple"]?
    – brian4342
    May 29, 2016 at 22:37
  • You should change the first ele to x which basically collects the items from b instead of a. Updated the code. May 29, 2016 at 22:41
  • Brilliant, thanks for your help. I am new to python and hadn't seen this before.
    – brian4342
    May 29, 2016 at 22:44
1

Using sets is actually of little benefit if you are not searching for exact matches, if the words always start with the same substring, sorting and bisecting will be a more efficient approach i.e O(n log n) vs O(n^2):

a = set(['this', 'is', 'an', 'apple!'])
b = set(['apple', 'orange'])

srt = sorted(a)
from bisect import bisect

inter = [word for word in b if srt[bisect(srt, word, hi=len(a))].startswith(word)]
0
0

The best thing to do is:

any(x in y for x in b for y in a)

It's a loop, but you can't escape that. Any solution will at least have an implied loop somewhere.

2
  • This works but only returns true or false. Is there a way to make is specify what the match is?
    – brian4342
    May 29, 2016 at 22:42
  • @ozgur's answer will work. Your question wording implied that you only wanted a boolean.
    – Alex Hall
    May 29, 2016 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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