递归地找到ID的孩子及其潜在的孩子

时间:2016-07-18 23:49:07

标签: python recursion sqlite tree

我创建了一个包含两列的表," TOP"和" UNDER"。 TOP是具有唯一ID的父列,UNDER包含基础ID,由"," s分隔。 UNDER中的项目也可以是" TOP"中列出的父项。列。

TOP     UNDER
----    --------
A       B
B       C,D
C       E,F
D       X,Y,Z
Z       J,K,L
E       V,M
F       G

我试图创建一个能够返回所有TOP的角色的函数。即:foo(" C")= [E,V,M,F,G]。 E有V,M。F有G.我迷失了如何实现递归部分。每当我尝试实现它时,我都会得到一个无限循环。

import sqlite3  
conn = sqlite3.connect("myTable.db") #Conn is a connection object that reps the db
conn.row_factory = sqlite3.Row #access columns of a query by name instead of index 
cursor = conn.cursor()   
id="C"    
cursor.execute("select * from myTable where id='%s'" %id)

def get_underlying(under_list, result_list=[]):
    if len(under_list) == 0:
        return result_list

    print("Query results for: select * from myTable where id='%s'" %(id))
    cursor.execute("select * from myTable where id='%s'" %id)
    r = cursor.fetchall()

    if r == []:
        return result_list

    under_list = r[0]['UNDER'].split(",") 
    for c in under_list:
        result_list.append(c)

    #???? lost on what to write
    if len(r) == 0:
        return
    elif len(r) == 1:
        return
    else
        return

print get_underlying("C")

Under_list将包含当前的UNDER值。即foo(" D"),under_list = [X,Y,Z]。然后我将每个元素附加到result_list。

我是否接近问题/以错误的方式实施?我可以帮忙做一些正确的帮助吗?我已经谷歌搜索了几个小时,但我似乎无法准确地说出我的搜索,以找到指南或解决方案。

1 个答案:

答案 0 :(得分:2)

修改

修改以处理图表中的循环。 (“TOP”和“UNDER”让我觉得这是一棵树,但也许这不是保证。)

from __future__ import print_function
import sqlite3

conn = sqlite3.connect('myTable.db')
conn.row_factory = sqlite3.Row
c = conn.cursor()

def initialize():
    c.execute('create table myTable (ID text, UNDER text)')

    data = [
        ['A', 'B'],
        ['B', 'C,D'],
        ['C', 'E,F'],
        ['D', 'X,Y,Z'],
        ['Z', 'J,K,L'],
        ['E', 'V,M'],
        ['F', 'G,C'], # note the cycle!
    ]

    for top, under in data:
        c.execute('insert into myTable values (?, ?)', (top, under))

    conn.commit()

def get_all_reachable(node_id, found=None):
    if found is None:
        found = set()

    c.execute('select * from myTable where id=?', (node_id,))
    rows = c.fetchall()

    if len(rows) == 0:
        return []

    for child in rows[0]['UNDER'].split(','):
        if child not in found:
            found.add(child)
            get_all_reachable(child, found)

    return found

if __name__ == '__main__':
    initialize()
    print(get_all_reachable('C'))

# Output:
# {'V', 'C', 'M', 'G', 'F', 'E'}