unbibium: (mugshot)
[personal profile] unbibium

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 the adder 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 as S[:0] returns an empty sequence of the same type as S, and the type 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.

This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

unbibium: (Default)
unbibium

June 2025

S M T W T F S
1234567
891011121314
151617 18192021
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 11th, 2025 01:52 pm
Powered by Dreamwidth Studios