captain holly java blog

Learning Python Painlessly

Posted in Python, TDD by mcgyver5 on October 26, 2011

I’ve been teaching a ten-year-old how to program and I can say that Python is a great first language.

  • avoids overhead of java by being weakly typed and not compiled
  • has both object oriented and functional features
  • widely supported
  • readable.
  • huge range of libraries and tools

It has been pretty quick for me to learn as well, as I have to study some to stay ahead of the ten-year-old.  I’ve found that a fast way to learn is to use the included unittest framework in Python and use the TDD model illustrated succinctly in the Bowling Game Kata and the Prime Factors Kata.  (What is a Kata?  Read This)

Ted Dzuiba memorably said:

You know what’s more awesome than spending my Saturday afternoon learning Haskell by hacking away at a few Project Euler problems? Fuck, ANYTHING.

and he has a point, but I watched my dad study medical journals when we were on vacation and I know that it takes time and hard work to keep up on technology.  Anyhow I’m amazed at how the combination of TDD and python helps me whiz through those Project Euler problems.

When one problem is done, the forums offer great insights.  For example, for problem number 4, I came up with:

def isPal(n):
  st = str(n)
  if st == st[::-1]:
    return True
    return False

def prods():
 prds = []
 largest = 1001
 for kk in range(999,100,-1):
    for kz in range(kk,100,-1):
       product = kk * kz
       if isPal(product):
          if product > largest:
             largest = product

   return largest

but a poster posted this one-liner:

print(max([x*y for x in range(900,1000) for y in range (900,x) if str(x*y) == str(x*y)[::-1]]))

I did not know you could do that.  the idiom “x*y for x in range….” and putting an if statement associated with a for statement are powerful tools.   This is referred to as List Comprehension.  The bit at the end is called “stride notation” (as I learned In this post about how to reverse a string).  It returns every nth member of a collection.  A negative n will start from the end of the collection and you can use that to reverse a string.

Negatives of Python:

  • The Python world seems to have impaled itself on a fence between 2.x and 3.x .  All the documentation out there is based on 2.x but they are trying to move to 3.2.  So, the forums are filled with answers like “in 3.2, you need print (x) instead of print x”
  •  When I encounter  __main__ and if __name__ == ‘__main__’:  my brain shuts down.
  • The included library timeit is the goofiest thing I’ve seen this year.  It wants you to put the code to time in a String and call exec on it.
Tagged with: