<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>thattommyhall.com &#187; Python</title>
	<atom:link href="http://www.thattommyhall.com/category/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.thattommyhall.com</link>
	<description>A Random Walk Through Idea Space</description>
	<lastBuildDate>Sun, 08 Jan 2012 11:42:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Infinite Prime Number Generator In Python</title>
		<link>http://www.thattommyhall.com/2010/10/18/prime-gen/</link>
		<comments>http://www.thattommyhall.com/2010/10/18/prime-gen/#comments</comments>
		<pubDate>Mon, 18 Oct 2010 12:50:35 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[euler]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.thattommyhall.com/?p=321</guid>
		<description><![CDATA[I was looking at this article (The Genuine Sieve of Eratosthenes / PDF) about a common functional prime number generator that is mistakenly called the Sieve of Eratosthenes. It is quite complicated, section 2 deals with the performance of the naive algorithm and 3 implements the sieve properly. I could not quite grok the Haskell [...]]]></description>
			<content:encoded><![CDATA[<p>I was looking at this article (<a href="http://lambda-the-ultimate.org/node/3127">The Genuine Sieve of Eratosthenes</a> / <a href="http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf">PDF</a>) about a common functional prime number generator that is mistakenly called the Sieve of Eratosthenes.</p>
<p>It is quite complicated, section 2 deals with the performance of the naive algorithm and 3 implements the sieve properly. I could not quite grok the Haskell but the following quote helped me know what was going on </p>
<blockquote><p>Whereas the original algorithm crosses off all multiples of a prime at once, we perform these “crossings off” in a lazier way: crossing off just-in-time. For this purpose, we will store a table in which, for each prime p that we have discovered so far, there is an “iterator” holding the next multiple of p to cross off. Thus, instead of crossing off all the multiples of, say, 17, at once (impossible, since there are infinitely many for our limit-free algorithm), we will store the first one (at 17 × 17; i.e., 289) in our table of upcoming composite numbers. When we come to consider whether 289 is prime, we will check our composites table and discover that it is a known composite with 17 as a factor, remove 289 from the table, and insert 306 (i.e., 289+17). <strong>In essence, we are storing “iterators” in a table keyed by the current value of each iterator.</strong></p></blockquote>
<p>Here it is using a dictionary for each composite number with a list of increments it was reached by:</p>
<pre class="brush: python; title: ; notranslate">
from itertools import count

def gen_primes():
    yield 2
    def update_composites(number,increment):
        try:
            composites[number] += [increment]
        except:
            composites[number] = [increment]

    composites = {4:[2]}

    c = count(3)
    while 1:
        #print composites
        next = c.next()
        smallest = min(composites.keys())
        incs = composites[smallest]
        del composites[smallest]
        for inc in incs:
            update_composites(smallest+inc,inc)
        if next &lt; smallest:
            yield next
            c.next()
            update_composites(next**2,next)

g=gen_primes()

for i in range(100):
    print g.next()
</pre>
<p>(On <a href="http://github.com/thattommyhall/Project-Euler/blob/master/PrimeGen.py">Github</a>)</p>
<p>They mention a speedup moving to a <a href="http://docs.python.org/library/heapq.html#theory">heapqueue</a> as the data structure (as we just take the lowest each lookup) so I implemented that too, here is the code</p>
<pre class="brush: python; title: ; notranslate">
from itertools import count
from heapq import heappush,heappop

def gen_primes():
    yield 2

    def update_composites(number,increment):
        heappush(composites,(number,increment))
    composites = [(4,2)]

    c = count(3)

    while 1:
        #print composites
        smallest,increment = heappop(composites)
        update_composites(smallest+increment,increment)
        if composites[0][0] == smallest:
            continue
        next = c.next()
        if next &lt; smallest:
            yield next
            c.next()
            update_composites(next**2,next)

g=gen_primes()

for i in range(100):
    print g.next()
</pre>
<p>(On <a href="http://github.com/thattommyhall/Project-Euler/blob/master/PrimeGen2.py">github</a>)</p>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://www.thattommyhall.com/2010/10/18/prime-gen/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.thattommyhall.com/2010/10/18/prime-gen/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning Ruby: methods vs procs (or Ruby vs Python?)</title>
		<link>http://www.thattommyhall.com/2010/10/04/learning-ruby-methods-vs-procs-or-ruby-vs-python/</link>
		<comments>http://www.thattommyhall.com/2010/10/04/learning-ruby-methods-vs-procs-or-ruby-vs-python/#comments</comments>
		<pubDate>Mon, 04 Oct 2010 13:03:46 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.thattommyhall.com/?p=292</guid>
		<description><![CDATA[I have been meaning to learn ruby for a while and the place I am working now uses a lot so I had another look at it. I read Learn To Program, a simple but good book and found the bit on blocks and procs etc pretty good and wanted to see if I could [...]]]></description>
			<content:encoded><![CDATA[<p>I have been meaning to learn ruby for a while and the place I am working now uses a lot so I had another look at it. I read Learn To Program, a simple but good book and found the bit on blocks and procs etc pretty good and wanted to see if I could do the stuff in Python as well. Python has anonymous &#8220;lambda&#8221; functions but they are limited to one line a subset of the syntax which is a bit annoying sometimes. My worry with methods in Ruby is that they are not first class, I think because you can omit parenthesis and so you have no way of referring to them without invoking them. </p>
<p>I remembered this while reading the SICP book, the question was about the difference between this program in applicative and normal order evaluation</p>
<pre class="brush: plain; title: ; notranslate">(define (p) (p))

(define (test x y)
  (if (= x 0)
      0
      y))</pre>
<p>It rang a bell as <strong>(define (p) p)</strong> does not go into an infinite loop if you invoke p. In lisp <strong>(p)</strong> calls the procedure p with no arguments whereas <strong>p</strong> is just a reference to the function. In python <strong>someinstance.method</strong> refers to the method, <strong>someinstance.method()</strong> calls it, Ruby seems to need Proc objects to get around this (IMHO as a beginner!, see the end for John Leach&#8217;s lovely response via email at the time)</p>
<p>I redid all the examples from the book in Python</p>
<p><strong>Eg 1</strong><br />
Ruby</p>
<pre class="brush: ruby; title: ; notranslate">
def maybe_do some_proc
  if rand(2) == 0
    some_proc.call
  end
end

def twice_do some_proc
  some_proc.call
  some_proc.call
end

wink = Proc.new do
  puts '&lt;wink&gt;'
end

glance = Proc.new do
  puts '&lt;glance&gt;'
end
</pre>
<p>Python</p>
<pre class="brush: python; title: ; notranslate">
import random

def maybe_do(some_proc):
    if random.choice(range(2)) == 0:
        some_proc()

def twice_do(some_proc):
    some_proc()
    some_proc()

def wink():
    print 'wink'

def glance():
    print 'glance'

for i in range(5):
    print 'running for i=',i
    maybe_do(wink)
</pre>
<p><strong>Eg2</strong><br />
Ruby</p>
<pre class="brush: ruby; title: ; notranslate">
def do_until_false first_input, some_proc
  input = first_input
  output = first_input
  while output
    input = output
    output = some_proc.call input
  end
  input
end

build_array_of_squares = Proc.new do |array|
  last_number = array.last
  if last_number &lt;= 0
    false
  else
    # Take off the last number...
    array.pop
    # ...and replace it with its square...
    array.push last_number*last_number
    # ...followed by the next smaller number.
    array.push last_number-1
  end
end

always_false = Proc.new do |just_ignore_me|
  false
end

puts do_until_false([5], build_array_of_squares).inspect

yum = 'lemonade with a hint of orange blossom water'
puts do_until_false(yum, always_false)
</pre>
<p>Python</p>
<pre class="brush: python; title: ; notranslate">
def do_untill_false(first_input, some_proc):
    input = first_input
    output = first_input
    while output:
        input = output
        output = some_proc(input)
    return input

def build_array_of_squares(array):
    last_number = array.pop()
    if last_number &lt;= 0:
        return False
    else:
        array.append(last_number * last_number)
        array.append(last_number - 1)
        return array

def always_false(just_ignore_me):
    return False

def just_ignore_me():
    pass

print do_untill_false([5], build_array_of_squares)
yum = 'lemonade with a hint of orange blossom water'
print do_untill_false(yum, always_false)
</pre>
<p><strong>Eg3</strong><br />
Ruby</p>
<pre class="brush: ruby; title: ; notranslate">
def compose proc1, proc2
  Proc.new do |x|
    proc2.call(proc1.call(x))
  end
end

square_it = Proc.new do |x|
  x*x
end

double_it = Proc.new do |x|
  x+x
end

double_then_square = compose double_it, square_it 

square_then_double = compose square_it, double_it

puts double_then_square.call(5) puts square_then_double.call(5)
</pre>
<p>Python</p>
<pre class="brush: python; title: ; notranslate">
def compose(proc1,proc2):
    def composed(x):
        return proc2(proc1(x))
    return composed

def square_it(x):
    return x**2

def double_it(x):
    return x*2

double_then_square = compose(double_it,square_it)
square_then_double = compose(square_it,double_it)

print double_then_square(5)
print square_then_double(5)
</pre>
<p><strong>Eg4</strong></p>
<pre class="brush: ruby; title: ; notranslate">
class Array
  def each_even(&amp;was_a_block__now_a_proc)
    # We start with &quot;true&quot; because
    # arrays start with 0, which is even.
    is_even = true
    self.each do |object|
      if is_even
        was_a_block__now_a_proc.call object
      end
      # Toggle from even to odd, or odd to even.
      is_even = !is_even
    end
  end
end

fruits = ['apple', 'bad apple', 'cherry', 'durian']
fruits.each_even do |fruit|
  puts &quot;Yum! I just love #{fruit} pies, don't you?&quot;
end

[1, 2, 3, 4, 5].each_even do |odd_ball|
  puts &quot;#{odd_ball} is NOT an even number!&quot;
end
</pre>
<p>Python</p>
<pre class="brush: python; title: ; notranslate">
class MyArray(list):
    def each_even(self):
        for i in range(len(self)):
            if i % 2 == 0:
                yield self[i]

fruits = MyArray(['apple', 'bad apple', 'cherry', 'durian'])

for fruit in fruits.each_even():
    print 'yum! I love %s pies, dont you?' % fruit

for odd_ball in MyArray([1,2,3,4,5]).each_even():
    print '%s is NOT an even number' % odd_ball
</pre>
<p><strong>Eg5</strong><br />
Ruby</p>
<pre class="brush: ruby; title: ; notranslate">
def profile block_description, &amp;block
  start_time = Time.new
  block.call
  duration = Time.new - start_time
  puts &quot;#{block_description}: #{duration} seconds&quot;
end

profile '25000 doublings' do
  number = 1
  25000.times do
    number = number + number
  end

  puts &quot;#{number.to_s.length} digits&quot;
  # That's the number of digits in this HUGE number.
end

profile 'count to a million' do
  number = 0 1000000.times do
    number = number + 1
  end
end
</pre>
<p>Python</p>
<pre class="brush: python; title: ; notranslate">
def profile(description, function):
    import time
    start_time = time.time()
    function()
    duration = time.time() - start_time
    print '%s: %s seconds' % (description, duration)
    print function.__name__
    print 'see, &quot;function.__name__&quot; can be used in place of description in python'

def count_to_a_million():
    number = 0
    for i in range(1000000):
        number = number+1

profile('count to a million', count_to_a_million)

def profiled(function):
    def new_function(*args, **kwargs):
        import time
        start_time = time.time()
        result = function(*args, **kwargs)
        print function.__name__, 'took', time.time() - start_time, 'secs'
        return result
    return new_function

@profiled
def count_to_a_million_again():
    number = 0
    for i in range(1000000):
        number = number + 1

count_to_a_million_again()
</pre>
<p>This uses <a href="http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Decorators">decorators</a>, a nice Python feature that uses higher order functions (and the fact functions are first class in python).</p>
<p><strong>In Conclusion</strong><br />
IMHO, at this point in my experience of Ruby, with all the disclaimers about my non expert status etc.<br />
Like: </p>
<ul>
<li>No restriction on complexity of anonymous functions</li>
</ul>
<p>Dont Like: </p>
<ul>
<li>Methods being different from Procs/Blocs, non-uniform syntax</li>
<li>Leaving out parenthesis (though I await DSL goodness later!)</li>
<li>&#8220;end&#8221; everywhere (I know the indentation thing in python is contentious!)</li>
</ul>
<p><strong>John Leach&#8217;s thought provoking tuppence</strong></p>
<blockquote><p>Young padawan, you look but you do not see, you will learn</p></blockquote>
<p>or rather</p>
<blockquote><p>Yeah, but blocks are closures Tom</p></blockquote>
<p>Tom goes to google and comes back with <a href="http://www.artima.com/intv/closures2.html">http://www.artima.com/intv/closures2.html</a><br />
Matz</p>
<blockquote><p>I think it&#8217;s not that useful in the daily lives of programmers. It doesn&#8217;t matter that much.</p></blockquote>
<p><strong>Then john came back with </strong></p>
<p><code>I can think of one example in Rails right away where it's useful, transactions:</code></p>
<pre class="brush: ruby; title: ; notranslate">
r = Record.new params[:record]

Record.transaction do
 r.save
 RecordLog.create(:text =&gt; &quot;created a new record&quot;)
end
</pre>
<p><code><br />
that code takes some input from a browser (in params), instantiates a<br />
new Record object, then writes it and a RecordLog entry to the database<br />
atomically.<br />
All the Record.transaction does is sends a BEGIN to the db server,<br />
executes the block, and sends a COMMIT (or a ROLLBACK if the block<br />
errors for any reason).<br />
The block needs access to the r object. We could have created that<br />
inside the block, but then it'd need access to the params object.  So<br />
without real closure support, Record.transaction would have had to<br />
support passing in arbitrary variables.<br />
Remember, that interview with Matz was in 2003 - more people are using<br />
Ruby for more things nowadays, for uses beyond the imagination of it's<br />
creator I'm sure <img src='http://www.thattommyhall.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </code></p>
<p><strong>Final Thoughts</strong><br />
I am waiting to be blown away by Ruby and Rails</p>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://www.thattommyhall.com/2010/10/04/learning-ruby-methods-vs-procs-or-ruby-vs-python/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.thattommyhall.com/2010/10/04/learning-ruby-methods-vs-procs-or-ruby-vs-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler 39</title>
		<link>http://www.thattommyhall.com/2008/04/12/project-euler-39/</link>
		<comments>http://www.thattommyhall.com/2008/04/12/project-euler-39/#comments</comments>
		<pubDate>Sat, 12 Apr 2008 18:49:57 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[euler]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.thattommyhall.com/2008/04/12/project-euler-39/</guid>
		<description><![CDATA[If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. {20,48,52}, {24,45,51}, {30,40,50} For which value of p &#60; 1000, is the number of solutions maximised? WARNING: CONTAINS MATHEMATICS You may remember from school (Difference of 2 squares) let and so [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.<br />
{20,48,52}, {24,45,51}, {30,40,50}<br />
For which value of p &lt; 1000, is the number of solutions maximised?</p></blockquote>
<p>WARNING: CONTAINS MATHEMATICS<br />
<span id="more-55"></span><br />
You may remember from school<br />
<img src="http://www.codecogs.com/eq.latex?a^2+b^2=c^2" alt="" /><br />
<img src="http://www.codecogs.com/eq.latex?a%5E2%20=%20c%5E2%20-%20b%5E2" alt="" /><br />
<img src="http://www.codecogs.com/eq.latex?a%5E2%20=%20%28c+b%29%28c-b%29" alt="" /><br />
(Difference of 2 squares)<br />
let<br />
<img src="http://www.codecogs.com/eq.latex?m=c+b" alt="" /><br />
and<br />
<img src="http://www.codecogs.com/eq.latex?n=c-b" alt="" /><br />
so<br />
<img src="http://www.codecogs.com/eq.latex?m+n=2c" alt="" /><br />
<img src="http://www.codecogs.com/eq.latex?m-n=2b" alt="" /><br />
and substituting these into <img src="http://www.codecogs.com/eq.latex?a^2=c^2-b^2" alt="" /><br />
gives<br />
<img src="http://www.codecogs.com/eq.latex?a=\sqrt{mn}" alt="" /><br />
Set <img src="http://www.codecogs.com/eq.latex?2p^2=m" alt="" /> and <img src="http://www.codecogs.com/eq.latex?2q^2=n" alt="" /> to get rid of that root and you have<br />
<img src="http://www.codecogs.com/eq.latex?a=2pq" alt="" /><br />
<img src="http://www.codecogs.com/eq.latex?b=p^2-q^2" alt="" /><br />
<img src="http://www.codecogs.com/eq.latex?c=p^2+q^2" alt="" /></p>
<p>Primitive triples are ones in lowest terms (if you know (3,4,5) you can get (6,8,10) etc by multiplying each side by some integer)<br />
If p and q are coprime and different parity you just get primitive ones (i did not bother and just used set() to remove dupes from the list)</p>
<p>Here is my code</p>
<pre class="brush: python; title: ; notranslate">
from __future__ import division
from collections import defaultdict
from time import time
     start = time()
counter = defaultdict(list)
    def triples():
    for q in range(1, 35):
        #35 is greater than sqrt(1000)
        for p in range(q+1, 35):
            a = p**2 - q**2
            b = 2 * p * q
            c = p**2 + q**2
            for m in range(1,int(1000/c)):
                #generate multiples till c is above 1000
                #triples with perimeter &gt; 1000 are filtered later
                yield (m*min(a,b),m*max(a,b), m*c)
    for triple in triples():
        perimeter = sum(triple)
        if perimeter &lt; 1001:
        counter[perimeter] += [triple]
&lt;p&gt;print set((counter[120]))
&lt;p&gt;maxlen = 1&lt;br /&gt;
for i in counter:
    length = len(set(counter[i]))&lt;br /&gt;
    if length &gt; maxlen:&lt;br /&gt;
        maxlen = length&lt;br /&gt;
        print i&lt;br /&gt;
end = time()&lt;/p&gt;
&lt;p&gt;print &quot;took &quot;, end-start&lt;/p&gt;
&lt;p&gt;</pre>
<p>Which outputs:<br />
<code>set([(24, 45, 51), (20, 48, 52), (30, 40, 50)])<br />
520<br />
528<br />
630<br />
660<br />
720<br />
840<br />
took  0.0140960216522</code></p>
<p>I tried brute forcing it today and knocked up the following</p>
<pre class="brush: python; title: ; notranslate">&lt;br /&gt;
from collections import defaultdict&lt;br /&gt;
counter = defaultdict(int)&lt;br /&gt;
from time import time&lt;/p&gt;
&lt;p&gt;def run():&lt;br /&gt;
	start = time()&lt;br /&gt;
	for perimeter in range(1,1001):&lt;br /&gt;
		#print perimeter&lt;br /&gt;
		for a in range(1,perimeter):&lt;br /&gt;
			for b in range(1,perimeter-a):&lt;br /&gt;
				c = perimeter - a - b&lt;br /&gt;
				if a**2 + b**2 == c**2:&lt;br /&gt;
					counter[a+b+c] += 1&lt;br /&gt;
	mosttriples = 0&lt;br /&gt;
	for i in counter:&lt;br /&gt;
		if counter[i] &gt; mosttriples:&lt;br /&gt;
			mosttriples = counter[i]&lt;br /&gt;
			print i&lt;br /&gt;
	end = time()&lt;br /&gt;
	print &quot;TOOK&quot;, end-start&lt;/p&gt;
&lt;p&gt;print &quot;without psyco&quot;&lt;br /&gt;
run()&lt;/p&gt;
&lt;p&gt;print &quot;with&quot;&lt;br /&gt;
import psyco&lt;br /&gt;
psyco.full()&lt;br /&gt;
run()&lt;br /&gt;
</pre>
<p>Which gives</p>
<pre class="brush: plain; title: ; notranslate">without psyco
516
520
528
630
660
720
840
TOOK 134.663383007
with
516
520
528
630
660
720
840
TOOK 21.0988409519
</pre>
<p>So psyco makes it 6 times faster but a smarter algorithm is 2000 times faster still.</p>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://www.thattommyhall.com/2008/04/12/project-euler-39/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.thattommyhall.com/2008/04/12/project-euler-39/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python talk for WYLUG, Ruby envy, Haskell Joy.</title>
		<link>http://www.thattommyhall.com/2007/12/27/python-talk-for-wylug-ruby-envy-haskell-joy/</link>
		<comments>http://www.thattommyhall.com/2007/12/27/python-talk-for-wylug-ruby-envy-haskell-joy/#comments</comments>
		<pubDate>Thu, 27 Dec 2007 12:05:38 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.thattommyhall.com/2007/12/27/python-talk-for-wylug-ruby-envy-haskell-joy/</guid>
		<description><![CDATA[I am just getting a talk ready for WYLUG on python. I sent Dave the following blurb: Why I love Python: A talk on the programming language Python, in 3 parts (feel free to leave in the interludes if you have had enough) Part 1: Past, Present, Future. A bit of history and the design [...]]]></description>
			<content:encoded><![CDATA[<p>I am just getting a talk ready for WYLUG on python.</p>
<p>I sent Dave the following blurb:</p>
<blockquote><p> Why I love Python:</p>
<p>A talk on the programming language Python, in 3 parts (feel free to<br />
leave in the interludes if you have had enough)</p>
<p>Part 1: Past, Present, Future.<br />
A bit of history and the design of the language, a look at all the<br />
implementations available today, quick tour of built-in and commonly<br />
used modules and future plans.</p>
<p>Part 2: Language overview<br />
A quick tour of the language: builtin types, control structures, using<br />
modules etc</p>
<p>Part 3: Recent Magic.<br />
Some relatively recent changes that make programming Python even more<br />
pleasurable.<br />
Decorators, Generators, List comprehensions, Iterators, Functools and<br />
anything else I can fit in.<br />
Again a whirlwind tour, but you should be impressed and want to read<br />
up on these some more</p></blockquote>
<p>I have been revisiting some of the Python talks I have watched over the last few years for ideas and will update my ComSci page with links.</p>
<p>I stumbled across some excellent video from RubyConf, particularly the <a href="http://rubyconf2007.confreaks.com/d2t1p3_rubinius.html" target="_blank">Rubinius</a> one. Rubinius is a ruby VM partially written in Ruby, taking some lessons from Python and Smalltalk. Some of the stuff he bigs up (compiling to bytecode automatically comes to mind) Python has had for ages, but the self hosting aspect is cool (not as cool as PyPy though). Rubinius seems to be doing what Avi Bryant suggested <a href="http://itc.conversationsnetwork.org/shows/detail3432.html" target="_blank">here,</a> learn from the Smalltalk guys and the <a href="http://research.sun.com/self/papers/papers.html" target="_blank">papers</a> from the Self team that Sun spun off and later bought back to do the hotspot VM for Java. Interesting times for dynamic languages, target the JVM, CLR, self host and generate code in other languages while always writing in the same fun language. I say Ruby envy only because I think the Ruby community does a better job of looking cool and exciting people than the Python one.</p>
<p>Now Haskell joy. After describing working through Yet Another Haskell Tutorial to the 2 friends doing it with me as &#8220;not an obviously pleasurable experience&#8221; I had a great moment on the train the other day looking at partial application.<br />
<code>(\y -&gt; y*3)</code><br />
is Haskell for the anonymous function  that takes y and multiplies it by 3 (I wish I had LaTeX here to draw the lamda calculus). What I like is that you can also write that as<br />
<code>(*3)</code><br />
While this example is trivial, what is happening is interesting. The compiler knows * is an infix operator that takes 2 arguments and that is has been supplied one and &#8220;partially applies&#8221; the function, making (*3) (a function that takes one argument). One more thing is changing prefix and infix operators around using ( _ ) and ` _ ` , for example:<br />
<code>3 * 5<br />
(*) 3 5<br />
</code><br />
<code>map (*2) [1,2,3]<br />
(*2) `map` [1,2,3]<br />
</code><br />
I hope this second example is clear, map usually is a prefix function that takes a function and a list and returns a list with the result of applying the function to each element (the return value here would be [2,4,6]). This flexibility is neat and is starting to make Haskell a joy to hack in.</p>
<p>Merry Christmas,</p>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://www.thattommyhall.com/2007/12/27/python-talk-for-wylug-ruby-envy-haskell-joy/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.thattommyhall.com/2007/12/27/python-talk-for-wylug-ruby-envy-haskell-joy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Second Python User Group meeting</title>
		<link>http://www.thattommyhall.com/2007/12/07/second-python-user-group/</link>
		<comments>http://www.thattommyhall.com/2007/12/07/second-python-user-group/#comments</comments>
		<pubDate>Fri, 07 Dec 2007 17:30:42 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.thattommyhall.com/2007/12/07/second-python-user-group/</guid>
		<description><![CDATA[I gave a talk at the second python user group in leeds on Wednesday. It was called &#8220;Anatomy Of A Python Program &#8211; How Much Can You Do In 0.1 KLOC?&#8221;. It is based on Peter Norvigs Sudoku solver. I had been thinking about doing it for WYLUG, possibly as a second talk after an [...]]]></description>
			<content:encoded><![CDATA[<p>I gave a talk at the second python user group in leeds on Wednesday. It was called &#8220;Anatomy Of A Python Program &#8211; How Much Can You Do In 0.1 KLOC?&#8221;. It is based on Peter Norvigs <a href="http://norvig.com/sudoku.html" target="_blank">Sudoku solver</a>. I had been thinking about doing it for WYLUG, possibly as a second talk after an intro to python. The slides were the same, but instead of looking at cool features of python that make the code so concise we critiqued it a bit and spoke about the style and possible speedups. The slides for the talk is <a href="http://www.thattommyhall.com/wp-content/uploads/SudukoPres.html" target="_blank">here</a>, but as I did not add any notes, you would be better off just reading Norvigs article (though the Javascript slideshow is cool, press t to toggle views)</p>
<p>The slideshow was made using rst2s5 and I am amazed how well it works. Restructuredtext is from Pythons Docutils and is a simple markup language designed to be readable as plain text, see <a href="http://docutils.sourceforge.net/rst.html">here</a> for details. Below is part of the code for my presentation </p>
<p><span id="more-31"></span></p>
<pre class="brush: python; title: ; notranslate">

==============================================================
Anatomy Of A Python Program - How Much Can You Do In 0.1 KLOC?
==============================================================

:Author: Tom Hall
 <img src='http://www.thattommyhall.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ate: 11pm Tues Dec 4th

The Problem - Sudoku
====================

::

   +----------+----------+----------+
   | A1 A2 A3 | A4 A5 A6 | A7 A8 A9 |
   | B1 B2 B3 | B4 B5 B6 | B7 B8 B9 |
   | C1 C2 C3 | C4 C5 C6 | C7 C8 C9 |
   +----------+----------+----------+
   | D1 D2 D3 | D4 D5 D6 | D7 D8 D9 |
   | E1 E2 E3 | E4 E5 E6 | E7 E8 E9 |
   | F1 F2 F3 | F4 F5 F6 | F7 F8 F9 |
   +----------+----------+----------+
   | G1 G2 G3 | G4 G5 G6 | G7 G8 G9 |
   | H1 H2 H3 | H4 H5 H6 | H7 H8 H9 |
   | I1 I2 I3 | I4 I5 I6 | I7 I8 I9 |
   +----------+----------+----------+

Setting The Scene
=================

::

    def cross(A, B):
        return [a+b for a in A for b in B]

    rows = 'ABCDEFGHI'
    cols = '123456789'
    digits   = '123456789'
    squares  = cross(rows, cols)
    unitlist = ([cross(rows, c) for c in cols] +
                [cross(r, cols) for r in rows] +
                [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')])
    units = dict((s, [u for u in unitlist if s in u])
                 for s in squares)
    peers = dict((s, set(s2 for u in units[s] for s2 in u if s2 != s))
                 for s in squares)

Taking in problems
==================

::

    def parse_grid(grid):
        &quot;Given a string of 81 digits (or . or 0 or -), return a dict of {cell:values}&quot;
        grid = 1
        values = dict((s, digits) for s in squares) ## To start, every square can be any digit
        for s,d in zip(squares, grid):
            if d in digits and not assign(values, s, d):
        	return False
        return values
</pre>
<p>The second talk went a bit over my head but was interesting, a declarative metaclass pattern. The chat after was great, everyone is interesting and excited about similar things to me.</p>
<p>I used Python the next day in work when our FTP server (a crappy windows app that I have disliked all the time I have been here) decided to recreate its password list as a 0 byte file and left us with no FTP. I took the time to do an upgrade to Filezilla and wrote a little python script to create entries in Filezillas xml config for all the users (though I had to manually create a .csv with all the usernames/passwords in). Simple things like this are another reason I like Python, it&#8217;s great tool for a SysAdmin to get those annoying little jobs done.</p>
<pre class="brush: python; title: ; notranslate">
import md5

users = open(&quot;usernames.csv&quot;,&quot;r&quot;)
outputxml = open(&quot;usernames.xml&quot;,&quot;w&quot;)

usernamestr = &quot;&quot;&quot;
&lt;User Name=&quot;%s&quot;&gt;
&lt;Option Name=&quot;Pass&quot;&gt;%s&lt;/Option&gt;
&lt;Option Name=&quot;Group&quot;/&gt;
&lt;Option Name=&quot;Bypass server userlimit&quot;&gt;0&lt;/Option&gt;
&lt;Option Name=&quot;User Limit&quot;&gt;0&lt;/Option&gt;
&lt;Option Name=&quot;IP Limit&quot;&gt;0&lt;/Option&gt;
&lt;Option Name=&quot;Enabled&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;Comments&quot;/&gt;
&lt;Option Name=&quot;ForceSsl&quot;&gt;0&lt;/Option&gt;
&lt;IpFilter&gt;
&lt;Disallowed/&gt;
&lt;Allowed/&gt;
&lt;/IpFilter&gt;
&lt;Permissions&gt;
&lt;Permission Dir=&quot;F:\FTPFILES\%s&quot;&gt;
&lt;Option Name=&quot;FileRead&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;FileWrite&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;FileDelete&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;FileAppend&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;DirCreate&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;DirDelete&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;DirList&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;DirSubdirs&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;IsHome&quot;&gt;1&lt;/Option&gt;
&lt;Option Name=&quot;AutoCreate&quot;&gt;0&lt;/Option&gt;
&lt;/Permission&gt;
&lt;/Permissions&gt;
&lt;SpeedLimits DlType=&quot;0&quot; DlLimit=&quot;10&quot; ServerDlLimitBypass=&quot;0&quot; UlType=&quot;0&quot; UlLimit=&quot;10&quot; ServerUlLimitBypass=&quot;0&quot;&gt;
&lt;Download/&gt;
&lt;Upload/&gt;
&lt;/SpeedLimits&gt;
&lt;/User&gt;
&quot;&quot;&quot;

def md5hash(password): return md5.new( password ).hexdigest()

for line in users.readlines():
    user , password = line.split(&quot;,&quot;)[0], line.split(&quot;,&quot;)[1][:-1]
    print user, password
    outputxml.write(usernamestr % (user, md5hash(password), user))

outputxml.close()
</pre>
<p>Passwords md5 hashed in 1 line and most of these 50 lines are the template for Filezilla. Definitely satisfies the mantra &#8220;Simple Things Should Be Simple, Complex Things Should Be Possible&#8221;. That the same language can be so applicable right across the complexity spectrum is amazing. I love the learning curve for Python, very smooth and it can take you very far.</p>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://www.thattommyhall.com/2007/12/07/second-python-user-group/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.thattommyhall.com/2007/12/07/second-python-user-group/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RubyQuiz 148 &#8211; Postfix to Infix</title>
		<link>http://www.thattommyhall.com/2007/12/01/rubyquiz-148-postfix-to-infix/</link>
		<comments>http://www.thattommyhall.com/2007/12/01/rubyquiz-148-postfix-to-infix/#comments</comments>
		<pubDate>Sat, 01 Dec 2007 23:32:05 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[RubyQuiz]]></category>

		<guid isPermaLink="false">http://www.thattommyhall.com/2007/12/01/rubyquiz-148-postfix-to-infix/</guid>
		<description><![CDATA[I have been meaning for some time to tackle the RubyQuiz problems in Python. The one from yesterday (#148) is quite interesting, taking postfix notated expressions and returning an infix version. For example 2 3 5 + * -&#62; 2 * (3 + 5) I spoilt it a bit by reading Reverse Polish Notation on [...]]]></description>
			<content:encoded><![CDATA[<p>I have been meaning for some time to tackle the RubyQuiz problems in Python.</p>
<p>The one from yesterday (#148) is quite interesting, taking postfix notated expressions and returning an infix version.</p>
<p>For example<br />
<strong>2 3 5 + *</strong> -&gt; <strong>2 * (3 + 5)</strong></p>
<p>I spoilt it a bit by reading Reverse Polish Notation on Wikipedia, which gave away how to evaluate the postfix expressions.</p>
<p>Here is my python code to evaluate postfix expressions<br />
<span id="more-28"></span></p>
<pre class="brush: python; title: ; notranslate">
ops = [&quot;+&quot;,&quot;*&quot;,&quot;/&quot;,&quot;-&quot;]

def evaluate(inputpfs):
    numstack =[]
    opstack = []
    for i in inputpfs.split():
        if i not in ops:
            numstack.append(i)
        else:
            right = numstack.pop()
            left = numstack.pop()
            #print (left + i +  right)
            numstack.append(str(eval(left + i +  right)))
    assert len(numstack) == 1
    return eval(numstack[0])
</pre>
<p>Then I realised all I needed to do was remove eval, add brackets and I would have what I needed.</p>
<pre class="brush: python; title: ; notranslate">
def bracket(somestring):
    return &quot;(&quot; + somestring + &quot;)&quot;

def post2infix(inputpfs):
    numstack = []
    opstack = []
    resultstr = &quot;&quot;
    for i in inputpfs.split():
        if i not in ops:
            numstack.append(i)
        else:
            right = numstack.pop()
            left = numstack.pop()
            newresult = &quot; &quot;.join([left, i, right])
            newresult = bracket(newresult)
            numstack.append(newresult)
    return numstack[0]
</pre>
<p>Then only printing brackets when you must. If the operation is &#8211; or /; you always need them around the right hand expression, unless is is a plain number as they are not associative. If the operation is +, you never need them. If the operation is * then you need them if you have + or &#8211; in the right hand expression. Note that left is always a plain number as only the top element of the stack is a compound expression</p>
<pre class="brush: python; title: ; notranslate">
def isnum (somestring):
    return all([i not in somestring for i in ops]) 

def post2infixpp(inputpfs):
    numstack = []
    opstack = []
    resultstr = &quot;&quot;
    for i in inputpfs.split():
        if i not in ops:
            numstack.append(i)
        else:
            right = numstack.pop()
            left = numstack.pop()
            if not isnum(right):
            #if (not all([i not in right for i in ops])):
                if i in [&quot;/&quot;, &quot;-&quot;]:
                    right = bracket(right)
                elif i==&quot;*&quot; and (&quot;-&quot; in right or &quot;+&quot; in right):
                    right = bracket(right)
            newresult = &quot; &quot;.join([left, i, right])
            numstack.append(newresult)
    return numstack[0]
</pre>
<p>A subtle bug means I could not do isnum inline (commented out, line 15 here), I had to add an auxiliary function. Though this way is more comprehensible, I cannot figure out why swapping lines 14 and 15 breaks the code.</p>
<p><strong>Testing</strong>: I know I should have done a bit more error checking in the above functions, but here is the little test sequence I wrote.</p>
<pre class="brush: python; title: ; notranslate">
eg1 = &quot;2 3 +&quot;
eg2 = &quot;2 3 5 + *&quot;
eg3 = &quot;56 34 213.7 + * 678 -&quot;
egs = [eg1,eg2,eg3]

for i in egs:
    print &quot;*********&quot;
    print i
    print evaluate(i)
    print post2infix(i)
    print post2infixpp(i)
    assert (#evaluate(i) ==
            eval(post2infix(i)) ==
            eval(post2infixpp(i))
           )
</pre>
<p>I had to comment out the evaluate(i) part of the assertion as it failed on eg3 due to some sort of floating point rounding error. I will try and track down why tomorrow.</p>
<pre class="brush: python; title: ; notranslate">
evaluate(eg3) == 13193.200000000001
eval(post2infixpp(eg3)) == eval(post2infix(eg3)) == 13193.199999999999
</pre>
<p>Get the file <a href="http://www.thattommyhall.com/rubyquiz148.py">Here</a></p>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://www.thattommyhall.com/2007/12/01/rubyquiz-148-postfix-to-infix/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.thattommyhall.com/2007/12/01/rubyquiz-148-postfix-to-infix/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tommys Project</title>
		<link>http://www.thattommyhall.com/2007/11/15/tommys-project/</link>
		<comments>http://www.thattommyhall.com/2007/11/15/tommys-project/#comments</comments>
		<pubDate>Thu, 15 Nov 2007 19:00:41 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.thattommyhall.com/2007/11/15/tommys-project/</guid>
		<description><![CDATA[I posted last time about TeXmacs and remembered the plugins for using it to display output from some of the superb free maths packages (which sometimes lack a nice display). The one I am excited about most is for SAGE. SAGE is written in python and leverages the hard work of the other projects (its [...]]]></description>
			<content:encoded><![CDATA[<p>I posted last time about TeXmacs and remembered the plugins for using it to display output from some of the superb free maths packages (which sometimes lack a nice display).</p>
<p>The one I am excited about most is for <a href="http://www.sagemath.org/index.html" target="_blank">SAGE</a>. SAGE is written in python and leverages the hard work of the other projects (its motto is <em>Building the Car Instead of Reinventing the Wheel</em>).  See the TeXmacs plugin <a href="http://www.sagemath.org:9001/TeXmacs" target="_blank">here</a> and some screenshots of SAGE <a href="http://www.sagemath.org/screen_shots/" target="_blank">here</a>.</p>
<p>I will take a look at the code and see if I can contribute anything, it will be nice to get involved in a big project.</p>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://www.thattommyhall.com/2007/11/15/tommys-project/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.thattommyhall.com/2007/11/15/tommys-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

