Explanations part are incorrect and generated IndexErrors

My bad, it was wrong the codes in the deleted post. See the one below.

The following codes in 5. Stack overflow Whoa! explanations part are incorrect and generated IndexErrors.

def power_set(set):
power_set_size = 2**len(set)
result =

for bit in range(0, power_set_size):
sub_set =
for binary_digit in range(0, len(set)):
if((bit & (1 << binary_digit)) > 0):
sub_set.append(set[bit])
result.append(sub_set)
return result

Traceback (most recent call last):
File “recursion.py”, line 16, in
print(power_set(test))
File “recursion.py”, line 9, in power_set
sub_set.append(set[bit])
IndexError: list index out of range

The line sub_set.append(set[bit]) is wrong because “bit” has the number of index from 2len(set) which is way more than the actual number of items in “set”. The correct codes I believe should be sub_set.append(set[binary_digit]) for that line and the entire set of codes can be updated as
def power_set(set):
power_set_size = 2
len(set)
result =

for bit in range(0, power_set_size):
sub_set =
for binary_digit in range(0, len(set)):
if ((bit & (1 << binary_digit)) > 0):
if set[binary_digit] not in sub_set:
sub_set.append(set[binary_digit])
result.append(sub_set)
return result
Output - [, [‘a’], [‘b’], [‘a’, ‘b’], [‘c’], [‘a’, ‘c’], [‘b’, ‘c’], [‘a’, ‘b’, ‘c’]]

1 Like