0

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-a, interval)):
        for c in list(np.arange(0, 101-a-b, interval)):
            for d in list(np.arange(0, 101-a-b-c, interval)):
                for e in list(np.arange(0, 101-a-b-c-d, interval)):
                    for f in list(np.arange(0, 101-a-b-c-d-e, interval)):
                        for g in list(np.arange(0, 101-a-b-c-d-e-f, interval)):
                            for h in list(np.arange(0, 101-a-b-c-d-e-f-g, interval)): 
                                for i in list(np.arange(0, 101-a-b-c-d-e-f-g-h, interval)):
                                    j = 100-a-b-c-d-e-f-g-h-i
                                    pairs.append([a,b,c,d,e,f,g,h,i,j])

Eventually, I want to obtain the pairs repeating for loops N times. The number of columns in pairs[] increases with the number of loops.

Can somebody possibly simplify the above code? I know one possible solution is using recursive function, but it is too challenging task for me, beginner. I do not care if your code includes other methods or syntax as long as it simplifies codes.

Thank you in advance!

1
  • Try to reduce the problem down to its most basic form. Commented Nov 1, 2020 at 14:09

1 Answer 1

2

The solution is the following recursive function:

def foo(n, wgt, s):
  if n==1:
    return [[100-s]]
  
  pairs = []
  for w in wgt:
    if s+w > 100: continue
    for 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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.