I am struggling with this exercise. It tells me to count all odd numbers present in an N-Ary. The exercise demands me to use recursion
Take a look at the following tree
5
________|_____________
| | |
20 4 6
| _____|______
11 | | | | |
10 2 9 8 7
__|__
| |
3 1
There are 12 numbers in it. Among these numers, 6 of them are odd which is the output i am looking for. However, the code i have written doesn't solve the issue and i don't understand why.
The function i have implemented returns 0 which is incorrect.
def es7(tree):
n = 0
for element in tree.f:
n = es7(element)
if element.id % 2 == 1:
n += 1
return n
class Nodo:
def __init__(self,V):
self.id=V
self.f=[]
################### DA QUI IN GIÙ SONO SOLO FUNZIONI NECESSARIE PER I TEST #####################
def fromLista(lista):
'''Crea l'albero da una lista [valore, listafigli]
In cui lista figli contiene alberi o e' la lista vuota. '''
r=Nodo(lista[0])
r.f=[fromLista(x) for x in lista[1]]
return r
def toLista(nodo):
''' Converte l'albero in una lista di liste [valore, listafigli]'''
return [nodo.id, [toLista(x) for x in nodo.f]]
Any suggestions?
Thanks