views:

98

answers:

2

Hello, I apologize in advance for the basic level of my question. I would like to the print the:

  • total number and identity of nodes that have 0 child, 1 child, 2 children, 3 children.
  • total number of node that have 0 parent, 1 parent, 2 parents, 3 parents.

here is my simple script. thanks. Vicinci

search = []
search += search_nodes()
node_father = []
node_child = []
for i in search:
    node_father += i.get_parents()
    node_child += i.get_children()
print "Total of nodes", len(search)
print "Total of parents", len(node_father)
print "Total of children", len(node_child)
+1  A: 

You can either create a map and do it yourself or use itertools.groupBy

1) Do-it-yourself way:

nodes_by_num_children={}
for node in search:
  children=len(node.get_children())
  if children not in nodes_by_num_children:
    nodes_by_num_children[children]=[]
  nodes_by_num_children[children].append(node)

for num, nodes in nodes_by_num_children.iteritems():
    print num
    for node in nodes:
        print node

2) Itertools way:

import itertools

search.sort(key=lambda x: len(x.get_children()))
for num_children,nodes in itertools.groupBy(search,lambda x: len(x.get_children())):
   print num_children 
   for node in nodes:
      print node
yu_sha
Thanks Yu_sha. I steel getting an error with 1)Do-it-yourself way:if children not in nodes_by_num_children:TypeError: unhashable type: 'list'
Lists cannot be keys of a dictionary, as they are mutable. Just make the third line say `children = tuple(node.getChildren())`.
jellybean
... or even better: Use ddaa's solution. :) The keys of the dictionary should be numbers.
jellybean
I am really sorry for my ignorance at the moment. I am just an absolute biginner. With the tuple at line 3 in the do it your self way I got the following error: children = tuple(node.getChildren())AttributeError: Node instance has no attribute 'getChildren'Help please
Sorry. You should replace i.get_children() with len (i.get_children())
yu_sha
I edited my code
yu_sha
+1  A: 
from collections import defaultdict

by_parents = defaultdict(list)
by_children = defaultdict(list)
for node in search_nodes():
    parents = node.get_parents()
    by_parents[len(parents)].append(node)
    children = node.get_children()
    by_children[len(children)].append(node)
ddaa