조언을 구합니다. NodeTree 클래스가 있습니다. 다음 create_T (d) 함수가 있습니다 이 함수는 트리를 나타내는 사전 d를 입력으로 받아 NodeTree 유형의 노드가있는 트리를 만듭니다. 어떻게해야합니까? 감사합니다 모두Python - Dictionary to NodeTree
답변
정보가 부족하여 몇 가지 가정을했습니다. 기본적으로 당신은 나무에서 어디서부터 시작할지를 알아야한다고 생각합니다. 임의의 지점을 선택하면 위쪽 및 아래쪽으로 작업해야합니다. 당신이 나무의 꼭대기 인 것을 운동 할 수있는 경우에 당신은 다만 아래쪽으로 일할 필요가있다. 어떤 노드가 다른 노드의 하위 노드가 아닌지 확인하기 위해 집합 비교를 수행하여 트리의 맨 위를 계산했습니다.
import itertools
# NodeTree
class Node(object):
def __init__(self, name):
self.name = name
self.children = []
def add_child(self, child_node):
self.children.append(child_node)
def __repr__(self):
if not self.children:
return '<%s/>' % self.name
else:
children = ''.join([repr(child) for child in self.children])
return '<%s>%s</%s>' % (self.name, children, self.name)
# create_T(d)
def create_tree(tree_dict):
# find which node is the top of the tree (assume it is well-formed)
all_leaves = set(itertools.chain(*tree_dict.values()))
top_of_the_tree = set(tree_dict.keys()) - all_leaves
def get_node(name):
node = Node(name)
for child_name in tree_dict[name]:
node.add_child(get_node(child_name))
return node
return get_node(top_of_the_tree.pop())
print create_tree({'a': ['b', 'c'],
'b': ['d'],
'c': ['e'],
'd': [],
'e': [],
'f': ['a']})
제공 :
<f><a><b><d/></b><c><e/></c></a></f>
노드를 가진 트리가 만들어집니다. 오류 : 'Type Unhashanle (dict)' – antia
생성됨 : all_leaves = set (itertools .chain (* tree_dict.values ())) – antia
이 문제를 해결하기 위해 이미 시도한 사항에 대해서는 언급하지 않았습니다. StackOverflow에는 트랙 레코드가 없습니다. 나는 당신의 질문을 따로 선택하고 많은 가정을하고 당신의 문제를 해결하여 완전한 실행 가능한 소스를 제공했다. 긍정적 인 피드백을 제공하는 대신 데이터를 시도 할 때 오류가 있지만 데이터가 무엇인지에 대한 세부 정보를 제공하지 않았다고 말한 것입니다. 바겐 세일이 끝나면 더 열심히 일해야합니다. 이 건설적인 피드백을 고려하십시오. –
- 1. ProviderCollection to Dictionary
- 2. Python pickling dictionary EOFError
- 3. dictionary in django python
- 4. Python : Best Dictionary implementation
- 5. Python Dictionary Ordersed Pairs
- 6. dictionary from csv file python
- 7. C# List <dictionary> To Json
- 8. Dictionary
- 9. in-place dictionary inversion of Python
- 10. .txt 파일을 dictionary (Python v2.7)로 처리하십시오.
- 11. 방법 : PIG의 Python UDF dictionary 반환 스키마
- 12. Python : '\\ x41'to '\ x41'
- 13. Java to Python RSA
- 14. Python loop to [: -1]
- 15. Mac to Windows Python
- 16. Python to Javascript
- 17. PHP to Python : Moovrelocator
- 18. Python, String to JSON?
- 19. JSON python to javascript
- 20. Ruby to Python bridge
- 21. Python JPEG to movie
- 22. Objective C to Python Serialization
- 23. sed regex to Python re
- 24. std :: map to Python 매핑
- 25. 도움말 번역 PYTHON to VB.NET
- 26. python httplib timeout to localhost
- 27. csh stdin to Python stdin?
- 28. Python write to line flow
- 29. Port C++ code to Python
- 30. access user dictionary android
당신이 나무 사전의 구조에 대한 자세한 내용을 제공 할 수 있습니까? 당신이 직면 한 어려움은 정확히 무엇입니까? –
두 개의 키를 입력으로 사용하는 사전 기능입니다. 'name'= 노드 이름 'children'= 자식 노드 목록의 값 (동일한 유형의 사전) 사전은 트리입니다. 사전 d를 입력으로 가져온 기능을 구현하는 데 어려움이 있습니다. NodeTree – antia