0

I want to make a function that takes a list as input and returns the sum of integers, real numbers, and complex numbers among the elements of the list. As elements of the list, data type objects other than integers, real numbers, and complex numbers are excluded when calculating the sum.

So I wrote the code like this way

def number_sum(lst):
    total = 0
    for e in lst:
        if type(e) == int or type(e) == float or type(e) == complex:
            total += e
    return total

x1 = [1, 3, 5, 7, 9]                     # 25
x2 = ["abc", [3, 5], 3.5, 2+3j, 4.5, 10] # 20 + 3j
x3 = []                                  # 0

print(number_sum(x1))
print(number_sum(x2))
print(number_sum(x3))

but I want I can take the x1, x2, x3 lists in input. How can I fix it?

2 Answers2

3

Use numbers.Number to check if a value is a number. From the documentation:

The root of the numeric hierarchy. If you just want to check if an argument x is a number, without caring what kind, use isinstance(x, Number).

Code

import numbers


def number_sum(lst):
    def get_numbers(l):
        """Generator that returns a flatten view a list"""
        for e in l:
            if isinstance(e, numbers.Number):
                yield e
            elif isinstance(e, (tuple, list)):
                yield from get_numbers(e)

    return sum(get_numbers(lst))


x1 = [1, 3, 5, 7, 9]
x2 = ["abc", [3, 5], 3.5, 2 + 3j, 4.5, 10]

print(number_sum(x1))
print(number_sum(x2))

Output

25
(28+3j)

Note that the function get_numbers is a generator that uses yield and yield from to flatten and filter the nested list. The result of get_numbers is then pass to the built-in function sum to actually sum the numbers.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
-3

you may use x = input("Enter the List: ") so that user can enter list in one line.
Import ast
If you want user to enter list as [1,2,3], then, use
import ast
x = input()
x = ast.literal_eval(x).
This will turn the string into a list.
finally your code will look like:

import ast

x = input("Enter the List: ")
x = ast.literal_eval(x)

Then, do the necessary function, that you want to do
Thanks to @Matthis and @S3DEV for improving suggesting the improvement

Ojas_Gupta
  • 107
  • 10
  • 1
    Might I suggest that you never use or advocate `eval` ever again until you read and understood "[Eval really is dangerous](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html)"? – Matthias Oct 26 '21 at 07:37
  • I whole-heartedly support @Matthias comment. In fact, beat me to it. Additionally, this *”If this answer solves your problem, kindly choose it as your answer”* is considered poor form. – S3DEV Oct 26 '21 at 07:46