[Tutor] What is the square bracket about?
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Sat Jul 22 22:03:53 CEST 2006
>> def adder1(*args):
>> print 'adder1',
>> if type(args[0]) == type(0):
>> sum = 0
>> else:
>> sum = args[0][:0]
>> for arg in args:
>> sum = sum + arg
>> return sum
This function looks overly enamored with Python slicing. *grin* Unless
I'm missing something, this function can be simplified to:
####################################################################
def adder(*args):
"""Sum up a list of args, assuming that the list is nonempty."""
running_sum = args[0]
for element in args[1:]:
running_sum = running_sum + element
return running_sum
####################################################################
That is, in stilted English: take the first element, and treat that as our
initial sum. Run through the rest of the elements, and add each such
element to our running sum. At the end of the iteration, we should be
done, and our running subtotal sum should be the sum of all the elements.
More information about the Tutor
mailing list