Reputation: 45
I have two strings containing words:
'dan esh gah'
and 'da nesh gah'
I need the intersection words, which is 'gah'
in this case.
I used this code
vocab=['dan esh gah']
gold=['da nesh gah']
s1 = ''.join(vocab)
s2=''.join(gold)
a=[]
track=[]
for k in range(len(s1)+1):
if k!=0:
for ka in range(0,len(s1)+1,k):
if s1[ka:ka+k] in s2:
track.append((len(s1[ka:ka+k])+1,s1[ka:ka+k]))
intersect=max(track)[1]
print(intersect)
but the answer is wrong:
sh ga
Please help me to solve this problem.
Upvotes: 2
Views: 2859
Reputation: 48077
You can do the intersection using &
on set()
object:
>>> s1='da nesh gah'
>>> s2='dan esh gah'
>>> set(s1.split()) & set(s2.split())
set(['gah'])
Here, I am firstly converting the string to list of words using str.split()
. set()
will convert the list to set object, on which you can find intersection between two sets using &
.
If you prefer functional style, you can use set().intersection()
to get the same result:
>>> set(s1.split()).intersection(s2.split())
set(['gah'])
Upvotes: 5