0

I have a function, f, and I am trying to evaluate it at x, y and z:

x = range(60,70)
y = range(0,5)
z = ["type1", "type2"]

results = [f(v,w,j) for v in x for w in y for j in z]

Right now "results" is a long vector, but I would like to get a matrix that looks something like this:

x1 y1 z1 f(x1,y1,z1)
x2 y1 z1 f(x2,y1,z1)
...
x9 y1 z1 f(x9,y1,z1)
x1 y2 z1 f(x1,y2,z1)
x2 y2 z1 f(x2,y2,z1)
...
x9 y2 z1 f(x9,y2,z1)
x1 y1 z2 f(x1,y1,z2)
...

covering all the possible combinations. So far I have tried this:

z = []
for v in x:
    for w in y:
        for j in z:
            z = [v, w, j, f(v,w,j)]

which is giving me the right format, but only evaluating one of the scenarios.

Any guidance is appreciate it . Thanks!

Dan
  • 35
  • 4
  • 1
    Possible duplicate of [How to generate all permutations of a list in Python](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) – ZdaR May 15 '18 at 02:28
  • Your desired results is not a matrix. – Scott Hunter May 15 '18 at 02:36
  • Maybe start by appending to `z` - `z.append((v, w, j, f(v,w,j))` instead of `z = [v, w, j, f(v,w,j)]`. – wwii May 15 '18 at 02:46

2 Answers2

1

Here is program which might help you:

x = range(60, 70)
y = range(0,5)
z = ["type1", "type2"]
ans = []
for i in x:
    for j in y:
        for k in z:
            ans.append([i, j, k, f(i, j, k)])

print(ans)
Shubham Agrawal
  • 298
  • 4
  • 10
-1

You can combine using numpy and porduct to get a matrix like answer.

from itertools import product

x = range(60,70)
y = range(0,5)
z = ["type1", "type2"]

l = (x,y,z)
res = list(product(*l))
res

Output:

[(60, 0, 'type1'),
 (60, 0, 'type2'),
 (60, 1, 'type1'),
 (60, 1, 'type2'),
 (60, 2, 'type1'),
 (60, 2, 'type2'),
 (60, 3, 'type1'),
 (60, 3, 'type2'),
 (60, 4, 'type1'),
 (60, 4, 'type2'),
 (61, 0, 'type1'),
 (61, 0, 'type2'),
 (61, 1, 'type1'),
.
.
.

To turn into matrix like with numpy:

import numpy as np

res = np.array(res).reshape(-1,len(l))

Output:

array([['60', '0', 'type1'],
       ['60', '0', 'type2'],
       ['60', '1', 'type1'],
       ['60', '1', 'type2'],
       ['60', '2', 'type1'],
       ['60', '2', 'type2'],
       ['60', '3', 'type1'],
       ['60', '3', 'type2'],
       ['60', '4', 'type1'],
               .
               .
               .
R.yan
  • 2,214
  • 1
  • 16
  • 33
  • `itertools.product` is probably a better way to produce all the argument combinations but I think the OP is having trouble saving all the results. ... `[(vi, wi, ji, f(vi,wi,ji)), ...]` – wwii May 15 '18 at 02:50
  • Yes, exactly what wii said, but I like the intertools way to generate the arguments, so thanks for sharing! – Dan May 15 '18 at 02:55
  • @DanR.- for your purpose `for v,w,j in itertools.product(x,y,z): ...do something with v,w,j` – wwii May 15 '18 at 03:03