I'm having trouble finding a combination of 3D arrays using Python.
The li numbers correspond to li1-3 respectively, and I would like to find a 3D array lifin that represents the result.
start=0
goal = 10
li1 = [2,3]
li2 = [5,7]
li3 = [8,9]
li = [1], [1,2], [2,3], [1,2,3]]
The starting point is 0 and the ending point is 10.
For example, li[1]=[1,2], but this represents start→li1→li2→goal, and as a result, I would like you to derive the following.
[[0,2,5,10], [0,2,7,10], [0,3,5,10], [0,3,7,10]
Finally, I would like to ask for the results like the one below.
lifin=[[0,2,10],[0,3,10]],
[[0,2,5,10],[0,2,7,10],[0,3,5,10],[0,3,7,10]],
[[0,5,8,10],[0,5,9,10],[0,7,8,10],[0,7,9,10]],
[[0,2,5,8,10],[0,2,5,9,10],[0,2,7,8,10],[0,2,7,9,10],[0,3,5,8,10],[0,3,5,9,10],[0,3,7,8,9,10],[0,3,7,9,10]]]
Thank you for your cooperation.
python
Preprocessing
>>>from ittertools import product
>>> start = 0
>> goal = 10
>>>M={}
>>> M[1] = [2,3]
>>> M[2] = [5,7]
>>>M[3] = [8,9]
>>li =[1],[1,2],[2,3],[1,2,3]]
Answer
>>>result=[]
>> for x in li:
... r = [ ]
... for y in product (*[M[k] for k in x]):
... r.append([start]+list(y)+[goal])
... result.append(r)
...
>>>
[[[0, 2, 10], [0, 3, 10]], [[0, 2, 5, 10], [0, 2, 7, 10], [0, 3, 5, 10], [0, 3, 7, 10]], [[0, 5, 8, 10], [0, 5, 9, 10], [0, 7, 8, 10], [0, 7, 9, 10]], [[0, 2, 5, 8, 10], [0, 2, 5, 9, 10], [0, 2, 7, 8, 10], [0, 2, 7, 9, 10], [0, 3, 5, 8, 10], [0, 3, 5, 9, 10], [0, 3, 7, 8, 10], [0, 3, 7, 9, 10]]]
Perhaps you were looking for itertools.product
.
All you have to do with itertools.product
is to put it together in a loop.
#!/usr/bin/python3
import itertools
start = [0]
goal=[10]
num_lists = [
None,
[2, 3],
[5, 7],
[8, 9]
]
choose_lists = [
[1],
[1, 2],
[2, 3],
[1, 2, 3],
]
result = [ ]
for choice_list in choice_lists:
choosen_num_lists=[num_lists[x] for x in choice_list ]
result.append([]
start+list(x)+goal
for x intertools.product(*chosen_num_lists)])
from print import print
print(result)
Results
[[0,2,10], [0,3,10]],
[[0, 2, 5, 10], [0, 2, 7, 10], [0, 3, 5, 10], [0, 3, 7, 10]],
[[0, 5, 8, 10], [0, 5, 9, 10], [0, 7, 8, 10], [0, 7, 9, 10]],
[[0, 2, 5, 8, 10],
[0, 2, 5, 9, 10],
[0, 2, 7, 8, 10],
[0, 2, 7, 9, 10],
[0, 3, 5, 8, 10],
[0, 3, 5, 9, 10],
[0, 3, 7, 8, 10],
[0, 3, 7, 9, 10]]]
© 2024 OneMinuteCode. All rights reserved.