HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Summing all parameters, except the last, which should be subtracted instead

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lasttheallsummingsubtractedinsteadshouldwhichparametersexcept

Problem

Working on some python koans and got one which states:

def f(a, b, z):

    """Rewrite this function to take an arbitrary number of arguments.

    It should add up all but the last argument and then subtract the
    last argument from the total.

    If no arguments are provided then return 0.
    """
    return a + b - z


My solution:

def f(*args):
    return sum(args[:-1]) - args[-1] if args else 0


This gives 2 out of 3 stars for a solution. I am not asking for help to get 3 stars specifically, but, rather for a review of what I have, and to see if there is perhaps something I am missing, or even if you consider my solution to be good as it is.

Out of interest, I've have also tried:

try:
    return sum(args[:-1]) - args[-1]
except IndexError:
    return 0


but that did not get 3 stars either.

What I am looking for is whether there is or isn't a more 'Pythonic' way of doing this, maybe reduce it even further than what I had there.

If there is only 1 value then the logic should give you the negative of your element.

Solution

Using an iterator is commonly considered more Pythonic than indexing, and avoiding an if makes code more beautiful in any language:

def f(*args):
    r = reversed(args)
    return -next(r, 0) + sum(r)

Code Snippets

def f(*args):
    r = reversed(args)
    return -next(r, 0) + sum(r)

Context

StackExchange Code Review Q#67358, answer score: 4

Revisions (0)

No revisions yet.