Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python Better ideas or ways to approach?

  1. Dec 23, 2016 #1

    ChrisVer

    User Avatar
    Gold Member

    I was trying to finish the assignments of this link
    https://ocw.mit.edu/courses/electri...ce-fall-2010/assignments/MIT6_034F10_lab0.pdf

    unfortunately they are not numbered, but I dealt with the Tree reference one. In particular, given a tree TREE and a list of indices, it will return the appropriate subtree. My python code looks like this:
    Code (Python):

    def depth(x):
        if not isinstance(x,(list,tuple)): return 0
        maxdep=0
        for element in x:
            maxdep = max( maxdep , depth(element) )
        return maxdep+1

    def tree_ref( tree, index):
        #Error if you ask for a deeper subtree than available
        if len(index)>depth(tree):
            return "ERROR \t tree_ref(): Your tree is smaller than what you asked"
        #main return
        if len(index)==1: return tree[index[0]]
        for i in range(len(index)):
            return tree_ref(tree[index[i]], index[i+1:])

    TREE=(((1, 2), 3), (4, (5, 6)), 7, (8, 9, 10))
    print  tree_ref(TREE, (1,1,1))
     
    As far as I've checked this code seems to work...Are there more clear or even optimal ways to do the job? thanks.
     
  2. jcsd
  3. Dec 24, 2016 #2

    Ibix

    User Avatar
    Science Advisor

    This structure seems a little odd - I think it's equivalent to
    Code (Python):
    return tree_ref(tree[index[0]],index[1:])
    Also, you've used a recursive approach. I'd probably use a loop-based approach, since I expect it would handle larger trees without falling over.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Better ideas or ways to approach?
  1. Project Ideas? (Replies: 1)

  2. Algorithm Ideas? (Replies: 0)

Loading...