-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum_powerset_using_binary_bits.py
43 lines (32 loc) · 1.4 KB
/
sum_powerset_using_binary_bits.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class SUMPOWERSET(object):
""" Sum powerset class """
def __init__(self):
""" init method """
self.result_list = []
def custom_combinations_binary(self, data_list):
""" To generate combinations of given data_list using binary """
# params
combinations_list = []
length_of_data_list = len(data_list)
# powerset size
powerset_size = pow(2, length_of_data_list)
for counter in range(powerset_size):
for element_counter in range(length_of_data_list):
if counter & (1<<element_counter):
combinations_list.append(data_list[element_counter])
return combinations_list
def sum_powerset(self, data):
""" To generate and return sum of powerset elements of given data """
try:
# converting data to list
data_list = list(data)
self.result_list = self.custom_combinations_binary(data_list)
# converting/mapping every element of result_list to integer
try:
result_elements = list(map(int, self.result_list))
except ValueError:
return -1
# returning sum of list elements
return sum(result_elements)
except Exception as exception:
return "Caught exception. {0}".format(str(exception))