Python Mystery Theatre -- Episode 3: Extend this

R

Raymond Hettinger

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

Raymond Hettinger

[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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top