![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
I was going through some of the exercises in Learning Python to see just how effective my Web-based self-teaching has been so far.
Chapter 4 on Functions has this exercise:
varargs. Generalize theadder
function you wrote in the last exercise to compute the sum of an arbitrary number of arguments, and change the calls to pass more or less than two. What type is the return value sum? (Hints: a slice such asS[:0]
returns an empty sequence of the same type asS
, and thetype
built-in function can test types.) What happens if you pass in arguments of different types? What about passing in dictionaries?
Basically, it wants me to write a function such that adder(x,y,z) == x+y+z
. And in Python, this means that strings and sequences can be concatenated with it, too, because that's what the native +
does. Obviously it wants me to use obfuscated things like type(S[:0])
. I figure, the +
sign gives me everything I need, why don't I take advantage of it?
My first solution looked like this:
def adder(*varargs):
if len(varargs) > 1:
return varargs[0]+adder(*varargs[1:])
if len(varargs) == 1:
return varargs[0]
if len(varargs) == 0:
raise IndexError
Yes, it calls itself recursively to keep adding things. It could obviously be optimized a little further. But then I remembered I read something about the built-in reduce
function somewhere, which would seem to do the trick here too:
adder = lambda S: reduce((lambda x,y: x+y), *S)
Almost certainly the fastest and shortest solution, but that's some pretty obscure stuff there. But the one I wrote before uses recursion, meaning the more arguments you pass it, the deeper it recurses, and that's not good. So here's my compromise:
def adder(firsvar, *othervars):
result = firstvar
for var in othervars:
result += var
return result
If only I were being graded.