The idea is that I am creating a decision tree based on N different possible layers. Only certain layers will affect the outcome in some cases, For example:
In this example, the square can be the outcome of both LL and RL, so this could be represented by "ANY", L.
The problem is that as I can't (to the best of my knowledge) represent "ANY" in python, and the idea is that I will have a dictionary that represents the path to the outcome, i.e.
My_dict = {tuple(["ANY",L]): "Square"}
I have to create an array that looks like the following to represent the possibilities:
[[L,R], L]
I want to be able to go from this list to outputting two lists of the shape:
[L,L], [R,L]
To represent all possible paths that lead to the square.
I feel like this should be doable with the itertools
module but I can't find anything myself, itertools.permutations
simply returns the positional changes in the list, i.e. [L,[L,R]]
and [[L,R],L]
.
Any suggestions would be great. Keep in mind that the solution needs to work for various data types, i.e. in actuality the tree structure options could be booleans or integers rather than just left or right.
CodePudding user response:
You can use itertools.product
:
from itertools import product
data = [['L','R'], ['L']]
result = list(product(*data))
print(result)
[('L', 'L'), ('R', 'L')]
CodePudding user response:
[still not sure on what do you want exactly]
Return all possible paths, included loops.
EDIT: for any data type
import itertools as it
def path_formatter(node):
node1, node2 = node
if len(node1) == 1:
node1 = node1[0]
if len(node2) == 1:
node2 = node2[0]
return node1, node2
p_lr = it.product('LR', repeat=2)
p_l = it.product('L', repeat=1)
p_r = it.product('R', repeat=1)
paths = map(path_formatter, it.combinations(it.chain(p_l, p_r, p_lr), r=2))
print(list(paths))
[original post - string only] Here all the possible paths joining any node of any layer, as a list of strings.
import itertools as it
def formatter(lr_tuple):
# format list of tuples to string
l, r = lr_tuple
if len(l) == 2:
l = '[' ','.join(l) ']'
if len(r) == 2:
r = '[' ','.join(r) ']'
return f'[{l},{r}]'
p_lr = it.product('LR', repeat=2)
p_l = it.product('L', repeat=1)
p_r = it.product('R', repeat=1)
nodes = [''.join(i) for i in it.chain(p_l, p_r, p_lr)]
nodes_pairs = it.combinations(nodes, r=2)
paths = map(formatter, nodes_pairs)
print(list(paths))
Output
# for any data type
[('L', 'R'), ('L', ('L', 'L')), ('L', ('L', 'R')), ('L', ('R', 'L')), ('L', ('R', 'R')), ('R', ('L', 'L')), ('R', ('L', 'R')), ('R', ('R', 'L')), ('R', ('R', 'R')), (('L', 'L'), ('L', 'R')), (('L', 'L'), ('R', 'L')), (('L', 'L'), ('R', 'R')), (('L', 'R'), ('R', 'L')), (('L', 'R'), ('R', 'R'))
# for string
['[L,R]', '[L,[L,L]]', '[L,[L,R]]', '[L,[R,L]]', '[L,[R,R]]', '[R,[L,L]]', '[R,[L,R]]', '[R,[R,L]]', '[R,[R,R]]', '[[L,L],[L,R]]', '[[L,L],[R,L]]', '[[L,L],[R,R]]', '[[L,R],[R,L]]', '[[L,R],[R,R]]', '[[R,L],[R,R]]']