1

my code so far:

import statistics

def nested_median(nest, templist=[]):
    
    if not nest:
        pass
    
    elif isinstance (nest[0], list):
        nested_median(nest[0]), nested_median(nest[1:])

    elif isinstance (nest[0], int):
        templist.append(nest[0])
        nested_median(nest[1:])
        return statistics.median(templist)

    else:
        nested_median(nest[1:])

I am trying to write a program that takes a arbitrarily nested lists as input and returns the median of all the integers in the list and/or sublists while ignoring all other elements. So for instance:

nested_median([3,2,"Hello",[1,5],("Hello", "world"),5,9.3]) == 3

I have come up with a solution above using a global variable, but this only works for one function call since templist dosen't get cleared.I have two questions:

  1. How would i go about clearing my global variable between function calls?

  2. How would i implement this without using a global variable?

EMiller
  • 817
  • 1
  • 7
  • 20

1 Answers1

0

The problem you described as "variable not cleared", is the "Mutable Default Argument" problem. Many blogs and tutorials were writtenn about it. Here on SO see: "Least Astonishment" and the Mutable Default Argument.


Below is a recursive generator for flattening arbitrary nested lists slightly modified to return only integers.

def ifl(x):
    if isinstance(x, list):  # to flatten tuples as well: isinstance(x, (list, tuple))
        for item in x:
            yield from ifl(item)
    elif isinstance(x, int):
        yield x
    # else: ignore x

test = [3,2,"Hello",[1,5],("Hello", "world"),5,9.3]
ints = list(ifl(test))  # [3, 2, 1, 5, 5]
# ... compute median
VPfB
  • 14,927
  • 6
  • 41
  • 75