Introduction to Set Operations
This problem asks:
Given: A positive integer n (n≤20,000) and two subsets A and B of {1,2,…,n}.
Return: Six sets: A∪B, A∩B, A−B, B−A, Ac, and Bc (where set complements are taken with respect to {1,2,…,n}).
References
Restate the problem
I’m going to get an integer less than 20,000, n, and two subsets, A and B, where both A and B are subsets of the counting numbers up to n. I need to return these six sets:
- The union of A and B.
- The intersection of A and B.
- The set difference A - B.
- The set difference B - A.
- The set complement of A.
- The set complement of B.
Solution steps
First, I struggled to read the sets out of the text file and build Python sets. My solution was to read the lines into lists, then construct sets from the lists as shown:
if __name__ == "__main__":
file_path = "/Users/robertbryan/Downloads/rosalind_seto.txt"
solution_path = "../solution-outputs/rosalind_seto.txt"
file = open(file_path, 'r')
lines = file.readlines()
n = lines[0]
A = lines[1]
B = lines[2]
B = str(B).replace('{', '').replace('}', '')
ListB = []
for item in B.split(','):
ListB.append(int(item))
SetB = set(ListB)
A = str(A).replace('{', '').replace('}', '')
ListA = []
for item in A.split(','):
ListA.append(int(item))
SetA = set(ListA)
n = int(n)
ListN = []
for i in range(1, n + 1):
ListN.append(i)
SetN = set(ListN)
I admit that this is an awkward and inefficient technique.
Once that was done, I used Python’s native set functions to write the six required sets to a file with a line break between each result.
file = open(solution_path, "x")
file.write(str(SetA.union(SetB)))
file.write('\n')
file.write(str(SetA.intersection(SetB)))
file.write('\n')
file.write(str(SetA.difference(SetB)))
file.write('\n')
file.write(str(SetB.difference(SetA)))
file.write('\n')
file.write(str(SetN.difference(SetA)))
file.write('\n')
file.write(str(SetN.difference(SetB)))
file.close()
My first attempt succeeded.
Post-solution notes
Challenges solved so far: 49
How many people solved this before me: 2,274
Most recent solve before me: yesterday
Time spent on challenge: 1 hour
Most time-consuming facet: reading the downloaded file into sets
Questions from others: Other solvers struggled with the size of the download file, but that wasn’t an issue for me.
Solutions from others: I learned that Python’s eval and input functions would have made putting the downloaded data into lists easy. All of my convoluted code above could have been replaced with:
n = eval(input())
a = eval(input())
b = eval(input())
Problem explanation: I could have written all the set operations myself. They’re not that complicated.
Closing thoughts: This was a gentle introduction to the most basic concepts of set theory.