J
J
Jan2020-06-12 23:57:04
Python
Jan, 2020-06-12 23:57:04

Created 4096 tree branches from for → for → for ... loops, etc. How can I find them now?

Need some advice, thanks everyone.
I master python, I study the possibilities.

I wanted to quickly create a binary tree, I decided with a for loop:

for wood_1 in range(1, 3):
    for wood_2 in range(1, 3):
    #и так 12 раз...


Inside the last loop, I collected all the branches into lists:

for wood_12 in range(1, 3):
    allwood = [wood_1, wood_2, ....., wood_12]
    print(allwood)


And I got 4096 wonderful lists (branches of a binary tree):

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1]
......

But the question is... How should I identify them? My attempts to shove this result into list() do nothing. Tell me, what is the elementary I miss out of ignorance?

Thanks to.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rais, 2020-06-13
@JanJarius

Find out for yourself what a b-tree is and what it eats with,
as well as what nodes and edges are (this is what graphs and trees consist of),
how to create a graph (tree) and traverse it.
Believe me, this is much more interesting than torturing the processor with 12 nested loops.
Well, the topic is probably like this:

import networkx as nx

G = nx.balanced_tree(2,12)
print (G.edges()) # выведет все дуги дерева
print (G.nodes()) # выведет все узлы дерева

And then do whatever detour you want along the tree.
Or like this:
Instead of print(allwood) store the path into a list:
all_paths.append(allwood).
Don't forget to initialize all_paths = [] before the loops.
Get a matrix (table), in each row of which one of the paths,
the column indicates the level of the graph (tree) - ready addressing.
If you need to store some object in each node, then use
networkx of course - it allows you to represent the node from a simple variable to storing an initialized instance of a class of any complexity.

S
Sergey Sokolov, 2020-06-13
@sergiks

Subtract 1 from the values ​​so that instead of 1 and 2 it becomes 0 and 1, and congratulations, you invented the binary system and wrote down consecutive numbers from 0 to 2^12 - 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question