Hercules
Hercules

Reputation: 1860

Having a generator expression as an input argument in Python

How can I interact with the values of a generator expression? For instance:

def sumValues(*args):
# compute the sum of values

sumValues(abs(x) for x in range(0,10))

When the range is known (e.g., we know the range is [0,10)), we can put a for loop, but what if the range is unknown?

Upvotes: 2

Views: 2625

Answers (2)

Copperfield
Copperfield

Reputation: 8510

it depend on how you want your function to be called, if you want to call it with list, generator, or more generally a iterable (anything that can be used in a for-loop) and imitate the behavior of the build-in sum then

def my_sum(iterable):
    total = 0
    for x in iterable:
        total += x
    return total

and use like

my_sum(range(10))
my_sum(abs(x) for x in range(0,10))
my_sum([1,2,3,4,5,6])

if you want to imitate the behavior of max and use it as above and also like my_sum(1,2), my_sum(1,2,3), my_sum(1,2,3,4,5,6,7), etc. then

def my_sum(*argv):
    total = 0
    values = None
    if len(argv) == 1:
        values = argv[0]
    else:
        values = argv
    for x in values:
        total += x
    return total

Upvotes: 1

Hercules
Hercules

Reputation: 1860

I figured. Here's the answer:

def sumValues(*args):
    # compute the sum of values
    total = 0
    for item in args[0]:
        total += item
    return total

print(sumValues(abs(x) for x in range(0,10)))
[output] => 45

Upvotes: 0

Related Questions