Python Mystery Theatre -- Episode 3: Extend this

Raymond Hettinger vze4rx4y at verizon.net
Tue Jul 22 09:27:21 CEST 2003


Here are few more mini-mysteries for your amusement
and edification.

Again in this episode, the program output is not shown.
Your goal is to predict the output and, if anything
mysterious occurs, then explain what happened
(in blindingly obvious terms).

This time, the extra credit is for picking-out the three
that surfaced as errors in my own, real code over
the past few years (the example context below may be
different, but the type of error occurred in real code).

Try to solve these without looking at the other posts.
Let me know if you learned something new along the way.


Enjoy,


Raymond Hettinger


ACT I ---------------------
def real(z):
    return hasattr(z, 'real') and z.real or z
def imag(z):
    return hasattr(z, 'imag') and z.imag or 0
for z in 3+4j, 5, 0+6j, 7.0, 8+0j, 9L:
    print real(z), imag(z)

ACT II ---------------------
uniq = {}
for k in (10, 'ten', 10+0j, u'ten', 'Ten', 't'+'en', 10.0):
    uniq(k) = 1
print len(uniq)

ACT III ---------------------
s = 'abracadabra'
for i in [3, 2, 1, 0]:
        print s[i:], s[-i:]

ACT IV ---------------------
pets = list('cat ')
pets += 'dog '
pets.extend('fish ')
print pets + 'python'

INTERMISSION (with output included, oh yeah! ------------
>>> import operator
>>> 1 - reduce(operator.add, [1e-7]* 10**7)
2.4983004554002264e-010

ACT V ---------------------
class Bin:
    numitems = 0
    contents = []

    def add(self, item):
        self.numitems += 1
        self.contents += [item]

laundry = Bin()
groceries = Bin()

laundry.add('shirt')
groceries.add('bananas')
groceries.add('nuts')
laundry.add('socks')
groceries.add('pretzels')

print laundry.numitems, laundry.contents
print groceries.numitems, groceries.contents


ACT VI -----------------------------------------
print "What is the technical name for this algorithm or transformation?"
a = range(0, 100, 10)
import random
random.shuffle(a)
print "Input:", a
swaps = 0
for i in range(len(a)):
    for j in range(i+1, len(a)):
    if a[i] > a[j]:
        i, j, a[i], a[j], swaps = j, i, a[j], a[i], swaps+1
print "Output:", a
print "Workload;", swaps







More information about the Python-list mailing list