I have a program that creates a tree by nesting the object creation as below. I know its not the correct way but I have to print the values at each level.
class Node(object):
def __init__(self, value, children):
self.value = value
self.children = children
exTree = Node(1, [
Node(2, []), Node(3, [
Node(4, [
Node(5, []), Node(6, [
Node(7,[])
])])])])
I tried accessing the values but couldn't find a way.
And I have to print the values as below:
print(treeToString(extree)
>1
>23
>4
>56
>7
UPDATE - I am able to achieve the following so far but its not in the correct format required. I have to create one function only.
def treeToString(exTree):
print(exTree.value)
for child in exTree.children:
treeToString(child)
treeToString(extree)
Output -
1
2
3
4
5
6
7
I have solved it in the following way:
def treeToString(extree):
rep = str(extree.value) + "\n"
return _treeToStringAux(extree, rep)
def _treeToStringAux(extree, rep):
for child in extree.children:
rep+= str(child.value)
if not (rep[-1] == "\n"):
rep+="\n"
for child in extree.children:
rep = _treeToStringAux(child, rep)
return rep
print(treeToString(exTree))
gives the result.
The part where I check the \n
is because due to the way I traverse the tree I sometimes get two newlines
I would use a generator to yield
one level at a time. This is very versatile as it lets you do all kinds of things with the output, not just print
.
def levels(trees):
if trees:
yield tuple([tree.value for tree in trees])
yield from levels([child for tree in trees for child in tree.children])
Example:
>>> list(levels([exTree]))
[(1,), (2, 3), (4,), (5, 6), (7,)]
From there, you can print if you like, or write pytests and doctests, or use in other applications.
for v in levels([exTree]):
print(' '.join(map(str, v)))
Output:
1
2 3
4
5 6
7
(Note: use ''.join(...)
above to suppress the space and match exactly your desired output, but I think it's more explanatory with the space).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.