''' This code illustrates the standard Python idioms for multiple
assignment. In class we used multiple assignment, but only with an
explicit comma-separated sequence on both sides of the equal sign. More
generally: the right-hand side can be *any* expression generating a
tuple, for instance a tuple return value. In particular, this can be
used in a recursive function returning a tuple.
There is an implicit assignment to the loop variable in the heading of
a for-loop. This assignment can also be multiple when the elements in
the for-loop's sequence are tuples. In my testing function I
illustrate this. You can see how handy it is. A variation on this
testing function would also be convenient for testing your homework.
'''
def threePowers(x, n):
''' Return (x**n, x**(n+1), x**(n+2) ) for small nonnegative
integer n. This is a silly algorithm, but it illustrates recursion
and multiple assignment.
'''
if n == 0:
return (1, x, x*x)
a, b, c = threePowers(x, n-1)
return b, c, c*x
def testing():
for (x, n) in [(3, 0), (2, 7), (-1, 27), (100, 8)]:
pn, pn1, pn2 = threePowers(x, n)
print 'x:', x, 'n:', n, 'powers:', pn, pn1, pn2
if (pn, pn1, pn2) != (x**n, x**(n+1), x**(n+2)):
print "ERROR"
print (pn, pn1, pn2), '!=', (x**n, x**(n+1), x**(n+2))
testing() # not inside a definition, so this automatically executes