If you're not familiar with Car Talk, it's a horrible talk radio show hosted by Tom and Ray Magliozzi (aka Click and Clack the Tappet brothers). Every week there is a new puzzler and every so often it's math oriented. After hearing this week's mathy puzzler, I thought it would be fun to dig into the archives (2009 and 2008) and try solving a few of them in Python. Here's what I came up with:

# 2008-10-20 The Perfect Square Dance!I'd like to see someone good with Ruby, Perl, or Lua do the same so we can compare solutions.

import itertools, math

for numbers in itertools.permutations(range(1, 19)):

for a, b in zip(numbers[::2], numbers[1::2]):

sqrt = math.sqrt(a + b)

if not str(sqrt).endswith('.0'):

break

if a == 1:

sallys_partner = b

elif b == 1:

sallys_partner = a

else:

print 'Sally danced with %d' % sallys_partner

break

# 2008-10-27 One is the Magic Number

print ''.join(str(n) for n in xrange(0, 1000000)).count('1')

# 2008-12-08 It's Math Time!

for ab in xrange(10, 100):

cab = ab ** 2

if str(cab)[1:] == str(ab):

print cab

break

# 2009-05-26 Equate This!

from __future__ import division # Avoids truncation.

import random

numbers = [2, 3, 4, 5]

operations = ['*', '**', '+', '-', '/']

while True:

random.shuffle(numbers)

random.shuffle(operations)

equation = ''

for i, number in enumerate(numbers):

equation += str(number)

if i < len(numbers) - 1:

equation += operations[i]

result = eval(equation)

if result == 26:

print equation

break

# 2009-06-08 Number One

print len([n for n in xrange(0, 1000000) if '1' not in str(n)])

Bug me in the office and I will write the other ones in Ruby, too:

ReplyDelete# 2008-10-27 One is the Magic Number

>> (0..999999).map{|i| i.to_s}.join.count("1")

=> 600000

# 2009-06-08 Number One

>> (0..999999).map{|i| 1 unless i.to_s.include? "1" }.compact.size

=> 531441

This information is very helpful. Very feasible for me as a reference. Thanks .. Oops .. Btw, your blog is very good and clean. I really like it:)

ReplyDeleteMake that "MIT graduates Tom and Ray Magliozzi!"

ReplyDeleteI'm sure Tom and Ray would consider 'horrible' to be high praise!

Love Python and love Car Talk!