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
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.