# Python Mystery Theatre -- Episode 3: Extend this

Discussion in 'Python' started by Raymond Hettinger, Jul 22, 2003.

1. ### Raymond HettingerGuest

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 ---------------------
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 = []

self.numitems += 1
self.contents += [item]

laundry = Bin()
groceries = Bin()

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 > a[j]:
i, j, a, a[j], swaps = j, i, a[j], a, swaps+1
print "Output:", a

Raymond Hettinger, Jul 22, 2003

2. ### Raymond HettingerGuest

[Steven Taschuk]
> > ACT VI -----------------------------------------
> > print "What is the technical name for this algorithm or transformation?"

> [...]
>
> Heh. Nice one.
>
> The technical name is "the identity transformation".

Ding ding! We have a winner.

Others thought the i,j swap was suspicious but did
not put the finger on left-to-right assignment undermining
the whole selection sort to make it do nothing at all.

Raymond Hettinger

Raymond Hettinger, Jul 22, 2003