This question already has answers here:
How to get all subsets of a set? (powerset)
(32 answers)
Closed 4 years ago.
[1,2,3]
I have this list and want to print all subsets of this list using recursion. I am getting the output using the following code but is there any better/easier way? Without typecasting it to a set.
def recur_subset(arr):
if len(arr)==0:
print(arr)
else:
for i in range(0, len(arr)):
print(arr[0:i+1])
for j in range(2, len(arr)):
print([arr[0], arr[j]])
return recur_subset(arr[1:len(arr)])
You could use itertools to do the heavy lifting:
import itertools
def recur_subset( s, l=None ):
if l == None:
l = len(s)
if l > 0:
for x in itertools.combinations( s, l ):
print(list(x))
recur_subset( s, l-1 )
Note: This only prints non-empty subsets; add else: print([]) at the end to include the empty subset.
Related
This question already has answers here:
Dynamic For Loops in Python
(2 answers)
Closed 2 years ago.
I wanted to calculate which whole numbers can be expressed by the square sum of three whole numbers. In my case until i,j,k all equal 4.
The (inelegant) code I used for this purpose is as follows:
nums = []
for i in range(4):
for j in range(4):
for k in range(4):
nums.append(i*i + j*j + k*k)
Is there a more pythonic or more elegant solution to this problem?
Ideally for as many variables (i, j, k, ..., n) as i want to.
You can use itertools.product to do this:
from itertools import product
for i, j, k in product(range(4), repeat=3):
# do something with i, j and k
If you don't know in advance how many variables you would need, you don't have to unpack the product into i, j and k. You Can leave it as:
for nums in product(range(4), repeat=3):
# do something with nums
If you want to do this for larger values, I would suggest using itertools
import itertools
def sumsq(x):
return sum(y * y for y in x)
max_integer = 4
num_terms = 3
num = [sumsq(x) for x in itertools.combinations_with_replacement(range(1, max_integer + 1), num_terms)]
Can be done in one line using list comprehension as:
l = [i*i + j*j + k*k for i in range(4) for j in range(4) for k in range(4)]
This question already has answers here:
How do I find the duplicates in a list and create another list with them?
(42 answers)
Closed 2 years ago.
Example 1:
input: [1,3,2,1,3,5]
Output: [1,3]
def duplicateNumber(mylist):
??
Thanks
Next time at least make an honest effort, describe the problem you are facing and then ask a question :
def duplicateNumber(x):
_size = len(x)
repeated = []
for i in range(_size):
k = i + 1
for j in range(k, _size):
if x[i] == x[j] and x[i] not in repeated:
repeated.append(x[i])
return repeated
This question already has answers here:
How to get all possible combinations of a list’s elements?
(32 answers)
Closed 4 years ago.
I want to write a code which gives me all the possible combinations of n elements in a k length k>n.The issue with this code is that i run out of memory quite fast.I was wondering if someone knew how to fix this with generators.I don't want to get all the possible combinations of a list elements. I want to get all the combinations of the elements in a certain length.
Thanks.
def allstrings(alphabet, length):
"""Find the list of all strings of 'alphabet' of length 'length'"""
if length == 0: return []
c = [[a] for a in alphabet[:]]
if length == 1: return c
c = [[x,y] for x in alphabet for y in alphabet]
if length == 2: return c
for l in range(2, length):
c = [[x]+y for x in alphabet for y in c]
return c
if __name__ == "__main__":
for p in allstrings(['a','b','c'],4):
print (p)
import itertools
itertools.combinations('alphabet', length)
From How to get all possible combinations of a list’s elements?
This question already has answers here:
Sort a list to form the largest possible number
(9 answers)
Closed 6 years ago.
x = [9,2,1]
l=[]
for i in range(len(x)):
p = max(x)
l.append(p)
x.remove(p)
print(l)
b = int(''.join(str(n) for n in l))
print(b)
The answer I got is 921
But if the list is [9,2,11].This won't work.
x = [9,2,11]
from itertools import combinations
l=combinations(x, len(x))
print max(map(lambda k: int("".join(map(str,k))),l))
You can use combinations here.
Output:
9211
This question already has answers here:
How to get the n next values of a generator into a list
(5 answers)
Closed 5 years ago.
What is the most efficient way to get a fixed number of items from a generator?
What I currently do is using zip and range. In this example I take
chunks of size 3 from the generator.
def f():
x = 0
while x < 21:
yield x
x += 1
g = f()
while True:
x = [i for _, i in zip(range(3), g)]
if not x:
break
print x
The background is that the database I use provides a generator object for query results. Than I fill a fixed size numpy array with data and process it as one batch.
Use itertools.islice:
import itertools
for elem in itertools.islice(f(), 3):
print elem
and directly into your numpy array:
my_arr = np.array(itertools.islice(f(), 3))