python - How to recursively generate a list of parent-child strings from an Adjacency List? -
summary:
i'm trying make recursive function takes data adjacency list , converts dot notation.
details:
i have data list of tuples (python). data sorted id
, limitation. there no restriction parents must listed before children: example, item #3 have parent item #7. there no (planned) limit number of generations.
id name parent | data = [ 1 0 | (1, 'a', 0), 2 b 1 | (2, 'b', 1), 3 c 1 | ... 4 d 2 | 5 e 2 | 6 f 3 | 7 g 2 | 8 h 6 | ... 9 4 | (9, 'i', 4)]
i want return list of strings in parent-child dot notation:
a a.b a.b.d a.b.d.i a.b.e a.b.g a.c a.c.f a.c.f.h
notice every name displayed - other algorithms i've found return items have no children.
things i've tried:
python code:
here's i've got far, based usf's data structure visualizations here.
if len(cat_list) == 0: return item in cat_list: parent_id = item[0] name = item[1] children = [_x _x in cat_list if _x[2] == parent_id] if len(children) == 0: # we're @ end return name else: sub_problem = cat_list[1:] sub_solution = create_categories(sub_problem) solution = "{}.{}".format(name, sub_solution) print(solution) return solution
but take 1 item , build way back:
d.e c.d.e b.c.d.e a.b.c.d.e
sql:
if data stored in sqlite database, , partially there following sql:
select t1.name level1, t2.name level2, t3.name level3, t4.name level4 category t1 left join category t2 on t2.parent = t1.id left join category t3 on t3.parent = t2.id left join category t4 on t4.parent = t3.id t1.name = 'a'
but has multiple issues:
- not scalable arbitrary depths
- does not return intermediate depths
because of these limitations, i've decided implement code in python.
research
i've looked @ bunch of different questions , websites, none have given me "eureka" moment, hence why i'm asking here.
this question pretty similar, in vb.net know nothing about. doesn't inform me on how perform concatenation.
this question pretty similar, again don't know language. seems lookup
function pretty similar python dict...
the data preparation step little hideous, because ids starting 1 need blocker element none @ position 0:
original = [(1, 'a', 0), (2, 'b', 1), (3, 'c', 1), (4, 'd', 2), (5, 'e', 2), (6, 'f', 3), (7, 'g', 2), (8, 'h', 6), (9, 'i', 4)] ids,data,parents = zip(*original) data =[none]+list(data) parents = [none]+list(parents)
this code work once input data in right format:
ids = range(1,10) parents = [none,0,1,1,2,2,3,2,6,4] data =[none,"a","b","c","d","e","f","g","h","i"] def get_parents(node): if not parents[node]: return data[node] return get_parents(parents[node])+data[node] id in ids: print ".".join(list(get_parents(id))) >>> a.b a.c a.b.d a.b.e a.c.f a.b.g a.c.f.h a.b.d.i
Comments
Post a Comment