This is from the Penn Treebank. Ultimately, I'd like to turn this into a binary tree, but first I need a way to traverse the tree, as-is.
Answer
def traverse(tree_of_lists):for item in tree_of_lists:if isinstance(item, list):for x in traverse(item):yield xelse:yield item
This is the "basic" solution -- can run in Python 2.7 and gives you an iterable that you can simply loop on. (In recent Python 3.* versions you'd use yield from item instead of the inner for loop).
The isinstance test is unpleasant but depending on your exact problem it may be the only way to distinguish a "scalar item" from a "sub-tree". There may be better ones but you don't give us enough information to be able to tell. For example, if all "leaves" (scalars) are strings, you might prefer to check for that (still an isinstance check, alas!).
I have a problem with printing my output from muscle aligning in python. My code is:from Bio.Align.Applications import MuscleCommandline
from StringIO import StringIO
from Bio import AlignIOdef align_v…
This is my python code for printing an absolute number. My function is returning type None. I am not getting what I have done wrong. Please help me. def n(num):if num<0:return (num*-1)no = input(&qu…
I am trying this code but it does not return total count for zero[x][y], in this case it should return 5 but all it displays 255 five time.
THIS CODE IS FOR CONNECTED COMPONENTS AND ZERO IS ONE COMPONE…
I want a program that prints Key and Value side by side for the following code:This is a Dictionary:d = {M: [Name1, Name2, Name3], F: [Name1,Name2,Name3]}I want the a program that prints in the followi…
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in the help center.Cl…
Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…
This question already has answers here:How to write the Fibonacci Sequence?(67 answers)Closed 6 years ago.n1 = 1
n2 = 1
n3 = n1 + n2
for i in range(10):n1 + n2print(n3)n1 = n2n2 = n3According to what …
Hi I am currently writing a snake game code and I am nearly finished however I am having difficulty writing a code which will cause the game to end if the head of the snake collides with its body, I th…
when I try to call the changeProfile function, I keep getting the error "getAuthCode is not defined" even though it is clearly defined. Why do I keep getting this error? What am I doing wron…