With the binomial tree, I am trying to make a nested list by level. Here is what I've done:
arrows = [("modifier","adverb1"),("noun","modifier"),("verb","noun"),("verb","adverb2"),("root","verb")]
dom_list = list(dict.fromkeys([a[0] for a in arrows]))
dom_list.pop()
depth = []
for a in dom_list:
MC = [v[1] for v in arrows if v[0] == a]
depth.append(MC)
con = []
for i in range(len(dom_list)):
c = [dom_list[i], depth[i]]
con.append(c)
The code lines result in:
[['modifier', ['adverb1']],
['noun', ['modifier']],
['verb', ['noun', 'adverb2']]]
What I want to make with this input is a nested list by level like:
['root', ['verb', ['noun', ['modifier', ['adverb1']], 'adverb2']]]
Is there any way to do this? Any help would be greatly appreciated.
Certainly not my most optimized code but it works on the data you provided as I understood your problem. Maybe this helps you in figuring out a more elegant solution:
def flat_gen(x):
# Flattens a nested list, taken from here but forgot the post
def iselement(e):
return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
for el in x:
if iselement(el):
yield el
else:
yield from flat_gen(el)
tmp = [list(x) for x in arrows]
tmp_new = []
for a in tmp:
for b in tmp:
if b[1] == a[0]:
b[1] = a
tmp_new.append(b)
else:
tmp_new.append(b)
# Find longest chain
idx_longest = [len(list(flat_gen(e))) for e in tmp_new].index(max([len(list(flat_gen(e))) for e in tmp_new]))
longest = tmp_new[idx_longest]
# Identify missing elements in longest chain
missing = set(flat_gen(arrows)).difference(list(set(flat_gen(longest))))
for m in missing:
for a in arrows:
if m in a:
outer = [""]
i = 0
outer[i] = longest
found = False
while not found:
print(a[0])
print(outer[i])
inner = outer[i][1]
if outer[i][0] == a[0]:
# Found position where to insert
outer[i].append(a[1])
found = True
else:
# Continue searching
outer.append(inner)
i += 1
a = list(a)
a[1] = outer[i]
print(a)
Returns:
['root', ['verb', ['noun', ['modifier', 'adverb1']], 'adverb2']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With