1

I have a list containing two words

list =  ["the","end"]

I have a list of tuples such as this

bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]

Is it possible to systematically go through each tuple in the bigramslist and see if both words in the list match any of the tuples in the bigramlist. And if so return true?

thanks

3
  • Are you looking for duplicates ? Commented Apr 14, 2011 at 11:55
  • 3
    Does (end, of) match (of, end), or do the tuples have to be in the same order to match? Commented Apr 14, 2011 at 12:03
  • yes the tuples have to be in the same order to match Commented Apr 14, 2011 at 13:06

2 Answers 2

13
>>> L1 = ["the","end"]
>>> bigramslist = [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ]
>>> tuple(L1) in bigramslist
True

edit for completeness:

>>> bigramsset = set( [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ] )
>>> L1 = ["the","end"]
>>> tuple(L1) in bigramsset
True

as jsbueno pointed out, using a set will result in a O(1) search time complexity where as searching the list is O(n). As a side note creating the set is also an additional O(n).

Sign up to request clarification or add additional context in comments.

2 Comments

If the order in bigramslist does not matter, it should be a set instead of a list - that will speed-up the comparisons a lot. Just do bigramslist = set(bigramslist) before checking for containement with the in operator.
@jsbueno: Indeed, although often you can construct a set in the first place instead of building a list, then building a set from that.
0

Not sure if this is what you're after:

>>> list = ["the", "end"]
>>> bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]
>>> def check(list, biglist):
...     return [(list[0], list[1]) == big for big in biglist]
... 
>>> check(list, bigramslist)
[True, False, False, False]
>>> 

Matches any of the compared values - you can then decide what to do if that list contains true.

Edit: Ok, kriegar's method is a lot better.

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.