in book composing program chapter 2.3, there is a function print_part() makes me confused (whole code here):
>>> def print_parts(tree, partition=[]):
if is_leaf(tree):
if root(tree):
print(' + '.join(partition))
else:
left, right = branches(tree)
m = str(root(tree))
print_parts(left, partition + [m])
print_parts(right, partition)
>>> print_parts(partition_tree(6, 4))
4 + 2
4 + 1 + 1
3 + 3
3 + 2 + 1
3 + 1 + 1 + 1
2 + 2 + 2
2 + 2 + 1 + 1
2 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1
this function print all the ways using parts up to 4 to partition 6. I've understand how the partition algorithm works in partition_tree() and have no problem to understand a partition tree:
4
_________________________
| |
4 3
_______ _____
| | | |
.. ... ... ...
but I still don't know how to print partition ways from a partition tree. especially these lines:
print(' + '.join(partition))
print_parts(left, partition + [m])
print_parts(right, partition)
# why call twice? and the recursion here didn't looks like the
# way the print_parts() called in the beginning.
update:
recursion here didn't looks like the way the print_parts() called in the beginning.
take an simpler args as example to illustrate my confusion:
>>> print_parts(partition_tree(3, 2))
2 + 1
1 + 1 + 1
the partition tree is:
2
--------------------------------
2 1
---------------- ------------------------
F 1 1 F
------ ------------
T F 1 F
-------
T F
or
[2, [2, [False], [1, [True], [False]]], [1, [1, [1, [True], [False]],[False]],[False]]]
the above list is first pass into the func print_parts() as trees's value.
when going to this line:
print_parts(left, partition + [m])
the left value is
[[2, [False], [1, [True], [False]]], [1, [1, [1, [True], [False]],[False]],[False]]]
it's no longer a tree because in the definition the tree should have a structure like: [node, [branch],[branch]]
. if so, the recursion cannot works.