Python Forum
Recursions with nested lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursions with nested lists
#1
I was able to write a function to recursively add the values within a nested list below:

def add_tree(tree):
    """
    Recursively computes the addition of all tree leaves.
    Returns an integer representing the addition.

    Inputs
       tree: A list (potentially containing sublists) that
       represents a tree structure.
    Outputs
       total: An int equal to the addition of all leaves of the tree.

    """

    if not isinstance(tree,list): 
        return tree
    else: 
        sumtree=0 
        for i in tree: 
            sumtree+=add_tree(i)
    return sumtree
This makes sense to me, especially after using Python Tutor.

The next part of my homework question asks us to define a new function that can carry out basic arithmetic operations on the leaves of a tree, i.e., the nested list. Operations are defined for us. I'll use the given addition operation as an example:

def summation(a,b):
    """
    Example operator function.
    Takes in two integers, returns their sum.
    """
    return a + b
In the new function we are asked to define op_tree, which takes three arguments:
op_tree(tree, op, base_call) where tree is the nested list, op is the operation function thus summation in my example, and base_call is the value the function returns when the tree is empty (0 for summation).

op_tree has to be recursive. I'm having trouble starting. It's unclear to me what I'm putting in as the arguments for the op, which requires two: a and b.
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,213 May-17-2020, 01:35 PM
Last Post: jefsummers
  Sum of Nested Lists raifuru42 2 4,313 Feb-19-2018, 02:57 PM
Last Post: mckingstar
  Combine nested lists in output python12345 2 2,747 Feb-17-2018, 01:38 PM
Last Post: python12345
  Nested loops, lists and if statements Liquid_Ocelot 10 8,860 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