I have a list of set
s like below. I want to write a function to return the elements that only appear once in those sets. The function I wrote kinda works. I am wondering, is there better way to handle this problem?
s1 = {1, 2, 3, 4}
s2 = {1, 3, 4}
s3 = {1, 4}
s4 = {3, 4}
s5 = {1, 4, 5}
s = [s1, s2, s3, s4, s5]
def unique(s):
temp = []
for i in s:
temp.extend(list(i))
c = Counter(temp)
result = set()
for k,v in c.items():
if v == 1:
result.add(k)
return result
unique(s) # will return {2, 5}
In mathematics, a set is a collection of unique elements. A set itself may be treated as a self-contained entity, such that you might represent an array of sets.
Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection. The rule for unique values is one we can use to our advantage here.
Even if one instance of the number 1 precedes the other, the axioms of the set theory do not allow to distinguish between two sets using the order of its elements, because the notion of order is not defined by the axioms of the theory. To do that, the ordered pair is defined as follows:
Do not think of 1 and 1 as "two elements of the same value". They are the same element really. And an element is either a member of a set or it is not. Informally, the "set" of members of your household should have a well defined size, and the number of nicknames a person has is unimportant to that set.
If you want the unique elements from both lists, this should work: x = [1,2,3,4] f = [1,11,22,33,44,3,4] res = list (set (x+f)) print (res) # res = [1, 2, 3, 4, 33, 11, 44, 22]
The hashing-based solution requires O (n) extra space. We can use bitwise AND to find the unique element in O (n) time and constant extra space. Create an array count [] of size equal to number of bits in binary representations of numbers. Fill count array such that count [i] stores count of array elements with i-th bit set.
You can use directly a Counter and then get the elements that only appear once.
from collections import Counter
import itertools
c = Counter(itertools.chain.from_iterable(s))
res = {k for k,v in c.items() if v==1}
# {2, 5}
I love the Counter-based solution by @abc. But, just in case, here is a pure set-based one:
result = set()
for _ in s:
result |= s[0] - set.union(*s[1:])
s = s[-1:] + s[:-1] # shift the list of sets
#{2, 5}
This solution is about 6 times faster but cannot be written as a one-liner.
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