In python, implement ’powerset’ and accompanying functions in the giving code. T
ID: 3722626 • Letter: I
Question
In python, implement ’powerset’ and accompanying functions in the giving code. The docstrings of each function elaborate on the constraints of each fn. Make sure to test your code.
Python code:
"""
Since elements of Python sets must be immutable,
a Python set cannot contain Python sets.
For example, a powerset cannot be represented using Python sets.
So we will simulate a set using lists.
For example, [[1,2], [1,3]] represents the set {{1,2}, {1,3}}.
This works, since lists do not have the immutability constraint.
"""
def randomSet (n, up):
"""Build a random 'set' of integers.
Be sure to guarantee the key property of a set: no duplicates.
>>> randomSet(4, 10)
[5, 3, 2, 8]
Params:
n (int): # of integers in the set
up (int): upperbound
Returns: (list) random 'set' of n integers between 0 and up, inclusive
"""
pass
def powerset (A):
"""Build the powerset of A.
>>> powerSet ([1,2])
[[], [1], [2], [1,2]]
Params: A (list): set of integers, represented internally as a list
Returns: (list) powerset of A, represented internally as a list
"""
pass
def printSet (L):
"""Print a 'set', using standard set notation.
To restore the correct interpretation, this function prints the 'set'
in true set notation.
Hint: you can print without adding a newline (see print documentation)
>>> printSet ([[1,2], [1,3]]
{{1,2}, {1,3}}
Params: A (list): set of integers
"""
pass
# an example of a test call
A = randomSet (5, 100)
# print (A)
print ("The powerset of ")
printSet (A)
print ("is")
B = powerset(A)
printSet (B)
print ("of size " + str(len(B))) # sanity check: should be 2^5 = 32
Explanation / Answer
""" Since elements of Python sets must be immutable, a Python set cannot contain Python sets. For example, a powerset cannot be represented using Python sets. So we will simulate a set using lists. For example, [[1,2], [1,3]] represents the set {{1,2}, {1,3}}. This works, since lists do not have the immutability constraint. """ import random def randomSet(n, up): """Build a random 'set' of integers. Be sure to guarantee the key property of a set: no duplicates. [5, 3, 2, 8] Params: n (int): # of integers in the set up (int): upperbound Returns: (list) random 'set' of n integers between 0 and up, inclusive """ result = [] # Go through N times for i in range(n): # Append a random int between 0 to up to result randint = random.randint(0, up) if randint not in result: result.append(randint) # return result return result def printSet(L): if (len(L) == 0): print "{}", print "{", for i in range(len(L) - 1): print L[i], ",", print L[i], "},", def powerset(A): x = len(A) result = [] for i in range(1Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.