rare = (["word1","word4","word5"])
freq = (["word1","word2","word3"])
unique = rare.intersection(freq)
print unique
error: AttributeError: 'list' object has no attribute 'intersection'
Am I not creating the sets correctly? They look like the examples in documentation -- but I can't seem to use normal set methods on them.
What is the proper syntax for creating sets if these are lists?
We can use a method called intersection in python and set intersection operator, i.e. &, to get the intersection of two or more sets. The set intersection operator only works with sets, but the set intersection() method can be used with any iterable, like strings, lists, and dictionaries.
The intersection of sets can be denoted using the symbol '∩'. As defined above, the intersection of two sets A and B is the set of all those elements which are common to both A and B. Symbolically, we can represent the intersection of A and B as A ∩ B.
What is the Time Complexity of Set Intersection in Python? The runtime complexity of the set. intersection() method on a set with n elements and a set argument with m elements is O(min(n, m)) because you need to check for the smaller set whether each of its elements is a member of the larger set.
This way you're not creating sets, just regular lists. Use the set
function:
rare = set(["word1","word4","word5"])
freq = set(["word1","word2","word3"])
Maybe you're confusing sets with tuples. A tuple is created with expressions between parenthesis, but you must provide at least a comma:
("this", "is", "a", "tuple")
("anotherone",)
Tuples are like immutable lists, but they're not sets.
On Python 2.7+, this is syntax for intersections using set operators:
>>> rare = {"word1", "word4", "word5"}
>>> freq = {"word1", "word2", "word3"}
>>> rare & freq
{'word1'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With