Tino Mosso
Tino Mosso

Reputation: 165

How to get the average of many lists embedded within each other?

This is the simplest case :

input [2,3,[4,6]]

The program should calculate the average of the list first, and then the average of 2 and 3, afterwards it should calculate the total average:

Upvotes: 3

Views: 91

Answers (1)

Pynchia
Pynchia

Reputation: 11580

A simple implementation that supports nested lists, does without any specific library and works with any python version:

def nested_avg(elements):
    try:
        seq = iter(elements)
    except TypeError:
        return elements
    s = 0
    while True:
        try:
            el = next(seq)
        except StopIteration:
            return s / len(elements)
        s += nested_avg(el)


l1=[2,3,[4,6]]
print(int(nested_avg(l1)))

l2=[2,3,[4,[5,7]]]
print(int(nested_avg(l2)))

Both l1 and l2 inputs produce the same result, i.e. 3

Note: the code does not cover all possible checks on the input data, up to you to make it production-ready :D

Upvotes: 2

Related Questions