Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError for recursive method in python

I have a recursive method problem with python, the code is this:

class NodeTree(object):
    def __init__(self, name, children):
        self.name = name
        self.children = children

    def count(self):
        # 1 + i children's nodes
        count = 1
        for c in self.children:
            count += c.count()
        return count


def create_tree(d):
    N = NodeTree(d['name'], d['children'])
    print N.count()

d1 = {'name':'musica', 'children':[{'name':'rock', 'children':[{'name':'origini','children':[]},
                                                               {'name':'rock&roll','children':[]},
                                                               {'name':'hard rock', 'children':[]}]},
                                   {'name':'jazz', 'children':[{'name':'origini', 'children':[{'name':'1900', 'children':[]}]},
                                                               {'name':'ragtime', 'children':[]}, {'name':'swing', 'children':[]}]}]}
tree = create_tree(d1)

The error is this:

count += c.count()
AttributeError: 'dict' object has no attribute 'count'

I tried anything but it doesn't work.

Anyway, any suggestions? Thanks!

like image 556
Lorenzo Viola Avatar asked Dec 06 '25 06:12

Lorenzo Viola


1 Answers

That's because Python dictionaries do not have a count method.

It'll help if we go over line by line what your code is actually doing.

    def count(self):
        # 1 + i children's nodes
        count = 1
        for c in self.children:      ## self.children is a list of dictionaries, so each c is a dictionary
            count += c.count()       ## We are getting .count() of c--which is a dictionary
        return count

This is because we passed d1['children'] as self.children, which is a list of dictionaries: [<dict>, <dict>, <dict>, ... ].

Rather than count(), what you should do is call len on the dictionary, to get the number of keys it has, thus becoming:

    for c in self.children:
        count += len(c)
like image 84
jdotjdot Avatar answered Dec 10 '25 00:12

jdotjdot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!