Home > Back-end >  count the sum of the nested list which contains strings and ints in python
count the sum of the nested list which contains strings and ints in python

Time:12-24

I know how to get the sum of a nested list that only contains numbers but how do i get the sum of a nested list that contains both strings and numbers?

def sum_all_numbers(seq):
    if not seq:
        return 0
    elif isinstance(seq[0], str):
        seq.remove(seq[0])
    elif isinstance(seq[0], list):
        return sum_all_numbers(seq[0])   sum_all_numbers(seq[1:])
    else:
        return seq[0]   sum_all_numbers(seq[1:])

I wanted to use double recursion to solve this problem but i don't manage to get the isinstance part right.

sum_all_numbers(["a", "b", ["c", 3, 4, [5, "d"], 10], 9])

is the input

CodePudding user response:

you can flatten all the list to a single list and then traverse and filter the list reuslt or while traversing the list filter the values.

using the second method adding code

# your code goes here
def get_sum(array: list):
    sum_ = 0
    for i in array:
        if type(i)==int:
            sum_ = i
        elif type(i) in [list, tuple]:
            sum_ = get_sum(i)
    return sum_


result = get_sum(["a", "b", ["c", 3, 4,(1,2,['a', 'b', [1,2,0]],'a',33), [5, "d"], 10], 9])
print(result)
# output 70

CodePudding user response:

I suggest using:

  • try/except to try adding numbers;
  • isinstance(x, (str, bytes)) to test if x is a string.

This way, you can add any numbers, not just int.

def sum_all_numbers(seq):
    result = 0
    for x in seq:
        try:
            result  = x
        except TypeError:
            if not isinstance(x, (str, bytes)):
                result  = sum_all_numbers(x)
    return result

print( sum_all_numbers(["a", "b", ["c", 3, 4, [5, "d"], 10], 9]) )
# 31

Note that this version will fail if the nested structure contains something that is not a number, a string, or an iterable:

sum_all_numbers([None, 3, 4])
# TypeError: 'NoneType' object is not iterable

To fix it, we can use a new try/except with iter:

def sum_all_numbers(seq):
    result = 0
    for x in seq:
        try:
            result  = x
        except TypeError:
            if not isinstance(x, (str, bytes)):
                try:
                    subseq = iter(x)
                    result  = sum_all_numbers(subseq)
                except TypeError:
                    pass
    return result

print( sum_all_numbers(["a", "b", ["c", 3, 4, [None, 12.0], [5, "d"], 10], 9]) )
# 43.0

I suggest reading the python sourcecode of more_itertools.collapse, for more ideas and error-handling to include in this function.

  • Related