I need to fix/modify this code I have here so that the output will be like this:
This is the code:
num_list = [1, 2, 3]
def combination_generator(num_list):
pool = tuple(num_list)
n = len(pool)
if range(num_list) > n:
return
indices = list(range(num_list))
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(num_list)):
if indices[i] != i + n - range(num_list):
break
else:
return
indices[i] += 1
for j in range(i+1, range(num_list)):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
print(combination_generator(num_list))
Note: I am not allowed to use any imports. so I can't use itertools. Also, it must also function with a higher number of values if added in the list.
Any help?
num_list = [1, 2, 3]
def combination_generator(attrs):
attrs = list(attrs)
if len(attrs) <= 1:
yield attrs
yield []
else:
for item in combination_generator(attrs[1:]):
yield [attrs[0]]+item
yield item
print(combination_generator(num_list))
print([i for i in combination_generator(num_list)])
print([set(i) for i in combination_generator(num_list)]) # if you nead a list[set]
output:
<generator object powerset at 0x0000022B7E8046D0>
[[1, 2, 3], [2, 3], [1, 3], [3], [1, 2], [2], [1], []]
[{1, 2, 3}, {2, 3}, {1, 3}, {3}, {1, 2}, {2}, {1}, {}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.