I have read that we can use map function to speed up for loops. But, in my code I have nested loops and I was wondering if there is anyway to speed up my code using map function or any other method.
import copy as cpy
import time
def powerset(s):
set =[]
x = len(s)
for i in range(1 << x):
set.append([s[j] for j in range(x) if (i & (1 << j))])
return set
def func1(Num):
Num_set = range(1, Num + 1)
A = []
for i in range(1, Num + 1):
my_set = cpy.deepcopy(Num_set)
my_set.remove(i)
my_subset = list(powerset(my_set))
for j in range(0, len(my_subset)):
name = "{r}:{s}".format(r=i, s=list(my_subset[j]))
A.append(name)
return A
start = time.time()
N = 10
A = func1(N)
end = time.time()
print("Run time:{t}".format(t=end - start))
The runtime of above code for N=10 is:
Run time:0.0383169651031
But the runtime for N=20 is around two minutes:
Run time:101.803981066
Any idea for speeding up the nested loop in function func1?
What this code does: Consider a number N =3. Function func1, first creates a list Num_set=[1,2,3]. Then for each element of this list say i, it generates all non-empty subsets of set(Num_set without i). For example if i=2, it adds "2,[]","2,[1]","2,[3]","2,[1,3]" to list A.
Many thanks!