Problem with trees exercises

L
Lorenzo_Cacciola (240 points)
1 2 3
asked Dec 11, 2021 in Exam exercises by Lorenzo_Cacciola (240 points)
edited Dec 11, 2021 by Lorenzo_Cacciola
I was trying to solve some exercises whit trees from the directory programming exercises and I noticed some problem:

1) the name of the file containing the class tree is called albero, but both in program.py and test.py it's imported as tree, and this raise an error.

2) I tried to print the tree, but if the tree has Childs then __repr__ doesn't work. and it raise this error: TypeError: expected 0 arguments, got 1 in the line 60 of albero.py

3)the lib test doesn't work because it says tree1 = tree.BinaryTree.fromList(tree), but tree doesn't exist
114 views

2 Answers

1899325 (5730 points)
0 0 15
answered Dec 11, 2021 by 1899325 (5,730 points)
A couple of days ago I found the same problems, but I forgot to mentioned it here, so thank you for having done this.

It probably has similar problems related with translation (n. 1 of your list) in other categories, I am not 100% sure but I remember similar things in the images exercises.
Luigi Pizza (6120 points)
11 20 65
answered Dec 11, 2021 by Luigi Pizza (6,120 points)

1)  importing a class in Python is the same as importing a function. So, for example, if the program file is called Albero.py and the class is called tree, then if your python file is in the same directory as Albero.py you can write

from Albero import tree

This shouldn't give you any error (check that they are in the same directory)

----------------------------------------------------------------------------------------------------

2) To print an object we don't use the function __repr__, but __str__ (You have to return the value you want to print).

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

( In general, __repr__ is used for the representation of the object when called in the terminal. __str__ works for the representation of the object through the functions str() and print()).

Also you should put the "self" in __repr__ even if it is not used. This is why it gave you the TypeError

----------------------------------------------------------------------------------------------------

3)  tree1 = tree.BinaryTree.fromList(tree)

This is probably a consequence of (1)