1
2

More than 3 years have passed since last update.

while, popを用いた木構造探索パターン(Python)

Posted at

概要

空配列がFalseと判定されるので、
whilepopによるシンプルな探索パターンを使う。

内容

環境

macOS Catalina
Python 3.7.0

準備

node.py
class Node:
    def __init__(self, name):
        self.name = name
        self.children = []
    def add_child(self, child):
        self.children.append(child)


A, B, C, D, E, F = Node('A'), Node('B'), Node('C'), Node('D'), Node('E'), Node('F')
A.add_child(B)
A.add_child(C)
B.add_child(D)
C.add_child(E)
C.add_child(F)

上記によって、下記の構造ができる。


A---B---D
  |
  --C---E
      |
      --F

実行

node.py
node_list = []
node_list.append(A)

while node_list:
    node = node_list.pop()
    for child in node.children:
        print(f'{node.name} has a child, {child.name}')
        node_list.append(child)
  • append:配列のお尻につける
  • pop:配列のお尻からとれる

蛇足

>>> bool(['a'])
True
>>> bool([])
False
>>> bool('hello')
True
>>> bool('')
False

参考にさせていただいた本

『ゼロから作るDeep Learning③ フレームワーク編』斎藤康毅著 O'REILLY

感想

木構造の探索のシンプルな実装がわかって良かった。

今後

機会があれば積極的に使っていきたい。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2