In: Computer Science
Write a program in python that reads the elements of a set from the keyboard, stores them in a set, and then determines its powerset. Specifically, the program should repeatedly ask the user:
Enter one more element ? [Y/N]
If the user answers Y then an new element is read from the keyboard:
Enter the new element in the set:
This cycle continues until the user answers N to the first question. At that point the program shall compute the powerset of the set of elements provided by the user, and print it to the screen. The powerset should not only be printed to the screen, but also stored in an instance of set.
Important: for what stated above, the elements of the powerset cannot be sets themselves. It is ok to store them in tuples. Note that while you can use a list to create a set (like in the example where we used list of chars), you cannot store lists in a set because of the same reason you cannot store sets inside a set. For example, the following code will give you an error
>>> A = [1,2] >>> B = [3,4] >>> C = [A,B] >>> D = set(C) 3 ---------------------------------------------------------------------------
TypeError Traceback (most recent call last) in ----> 1 D = set(C)
TypeError: unhashable type: ’list’
The reason is that D = set(C) tries to build a set of elements from the list C, and the elements of C are the lists A and B. On the contrary, E = set(A) would be ok, because it builds a set from the elements of A, and the elements of A are integers.
Code:
# input set
s = set()
while(True):
option = input('Enter one more element ? [Y/N] ')
if(option == 'N'):
break
val = int(input('Enter the new element in the set: '))
s.add(val)
powerset = set()
val = list(s) # convert input set s to list
n = len(val) # number of elements
# generate powerset using bitmasking
for i in range(1<<n):
curr = tuple([val[j] for j in range(n) if(i & (1<<j))]) # generate as tuple
powerset.add(curr) # add to powerset
# print the powerset
print(powerset)
Code screenshot:
code output
===========
The code along with comments and screenshot has been added. Bitmasking has been used to generate the powerset.
Please upvote.