2009-12-10 3 views
0

나는 내 질문의 기본 수준에 대해 미리 사과한다.파이썬 승계와 후손

  • 0 명의 자녀, 1 명의 자녀, 2 명의 자녀, 3 명의 자녀가있는 노드의 총 수와 ID입니다.
  • 부모가 1 명, 부모가 1 명, 부모가 2 명, 부모가 3 명인 노드의 총 수입니다.

여기 내 간단한 스크립트입니다. 덕분에 . Vicinci

1 itertools.groupBy

을 당신은지도를 만들 수 있습니다 그것은 자신을하거나 사용
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) 
+0

그 숙제입니까? 그렇다면 숙제 태그가 있어야합니다. – ddaa

+0

동의. 숙제 문제를 해결할 충분한 정보를 우리에게주지 않았습니까? 지금까지 해본 내용과 실패한 내용을 보여주십시오. –

답변

1

) - 그것 - 스스로 방법 :

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 방법 :

가져 오기 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 
1
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)