Python Simplifying Nested For Loops Using Recursive Function Or Other Methods
I would like to simplify the following codes: import numpy as np interval = 20 wgt = list(np.arange(0, 101, interval)) pairs = [] for a in wgt: for b in list(np.arange(0, 101-
Solution 1:
The solution is the following recursive function:
deffoo(n, wgt, s):
if n==1:
return [[100-s]]
pairs = []
for w in wgt:
if s+w > 100: continuefor t in f(n-1, wgt, s+w):
pairs.append([w] + t)
return pairs
And you can produce the desired pairs
list with:
import numpy as np
interval = 20
wgt = np.arange(0, 101, interval)
N = 10
pairs = foo(N, wgt, 0)
Post a Comment for "Python Simplifying Nested For Loops Using Recursive Function Or Other Methods"