Python Forum
Recursions with nested lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursions with nested lists
#3
(Oct-04-2019, 05:23 PM)ichabod801 Wrote: In your function, you have:
 sumtree+=add_tree(i) 
That is equivalent to:
 sumtree = sumtree + add_tree(i) 
Given that you want to replace a and b in a + b, what matches from your earlier code?

Thank you for the push. I ended up writing this

def op_tree(tree, op, base_case):
    """
    Recursively runs a given operation on tree leaves.
    Return type depends on the specific operation.

    Inputs
       tree: A list (potentially containing sublists) that
       represents a tree structure.
       op: A function that takes in two inputs and returns the
       result of a specific operation on them.
       base_case: What the operation should return as a result
       in the base case (i.e. when the tree is empty).
    """  
  
    if isinstance(tree,int):
        return op(base_case,tree)
        
    else:
        value=op(base_case,base_case)
        for i in tree:
            value+=op_tree2(i,op,base_case)
        return value
Which worked for the summation operation, but does not work for a product operation and I knew it was because I was using +=, which doesn't work for multiplication. However, going back to your comment after I tried this clarified things. I changed the code above incorporating your hint and I got it to work!
Reply


Messages In This Thread
Recursions with nested lists - by sashiessay - Oct-04-2019, 03:49 PM
RE: Recursions with nested lists - by ichabod801 - Oct-04-2019, 05:23 PM
RE: Recursions with nested lists - by sashiessay - Oct-05-2019, 11:40 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sorting nested lists in ascending order jszum 2 2,273 May-17-2020, 01:35 PM
Last Post: jefsummers
  Sum of Nested Lists raifuru42 2 4,352 Feb-19-2018, 02:57 PM
Last Post: mckingstar
  Combine nested lists in output python12345 2 2,794 Feb-17-2018, 01:38 PM
Last Post: python12345
  Nested loops, lists and if statements Liquid_Ocelot 10 8,987 Apr-23-2017, 02:02 PM
Last Post: Mekire

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020