I have the following python function to print all subsets of a list of numbers:
def subs(l):
if len(l) == 1:
return [l]
res = []
for sub in subs(l[0:-1]):
res.append(sub)
res.append([l[-1]])
res.append(sub+[l[-1]])
return res
li = [2, 3, 5, 8]
print(subs(li))
This returns:
[[2], [8], [2, 8], [5], [8], [5, 8], [2, 5], [8], [2, 5, 8], [3], [8], [3, 8], [5], [8], [5, 8], [3, 5], [8], [3, 5, 8], [2, 3], [8], [2, 3, 8], [5], [8], [5, 8], [2, 3, 5], [8], [2, 3, 5, 8]]
Which is not the expected answer. It looks like python takes the list l into the function by reference. So when I append l[-1], it appends the last element of original list, not the smaller list sent into the recursive method. Is there any way to solve this?
This could possibly be solved using tuples but I'm wondering if there is a solution using lists.
Python has itertools. combinations(iterable, n) which Return n length subsequences of elements from the input iterable. This can be used to Print all subsets of a given size of a set.
If a set contains 'n' elements, then the number of proper subsets of the set is 2n - 1. In general, number of proper subsets of a given set = 2m - 1, where m is the number of elements.
Python Set issubset() The issubset() method returns True if set A is the subset of B , i.e. if all the elements of set A are present in set B . Else, it returns False .
def subs(l):
if l == []:
return [[]]
x = subs(l[1:])
return x + [[l[0]] + y for y in x]
Results:
>>> print (subs([1, 2, 3]))
[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With