# Python

## Project Euler - Problem 17

It's been to long since I posted a solution to one of these challenges. How time flies when you're having fun.

Here's the problem:
`If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.`

``` ```

`If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?`

Here is the python code:

`#!/usr/bin/env python ones = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five',        '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '0': ''} tens = {'2': 'twenty', '3': 'thirty', '4': 'forty', '5': 'fifty',        '6': 'sixty', '7': 'seventy', '8': 'eighty', '9': 'ninety'} teens = {'10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thriteen',         '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen',         '18': 'eighteen', '19': 'nineteen'} hundreds = {0: 0, 1: "onehundredand", 2: "twohundredand",            3: "threehundredand", 4: "fourhundredand",            5: "fivehundredand", 6: "sixhundredand",            7: "sevenhundredand", 8: "eighthundredand",            9: "ninehundredand" } if __name__ == "__main__":    tot = 0    for h in xrange(10):        for y in xrange(1,100):            try:                t,o = tuple(str(y))                if t is '1':                    tot += len("{h}{t}".format(h=hundreds[h], t=teens[t + o]))                else:                    tot += len("{h}{t}{o}".format(h=hundreds[h], t=tens[t],                                                  o=ones[o]))            except ValueError:                    tot += len("{h}{o}".format(h=hundreds[h], o=ones[str(y)]))    tot += len('onethousand')    print tot`

Even though I wrote it, I still look at it and think "that's not mine." It's been a long time since I wrote a for loop within a for loop. There isn't anything wrong with it, it's just not my style. This time however I wasn't really able to come up with a solution that would allow me to break out of the two for loops.

The one part of the code that I was surprised "worked" war breaking up the digits by turning the number to a string then a tuple. This allowed me to easily test an exception. This exception will only be thrown 10% of the time. While exceptions might be expensive, the other 90% of the time the code hums along without using a conditional. Everything has costs, but I think that the cost of throwing an exception 10% of the time as opposed to testing a conditional 100% of the time is a cost I'm willing to accept.

I will admit that I did not code up another solution in a different programming language. While part of that is due to being lazy - it's good for the soul once and a while - I'm also not sure how I can code this up in a functional language. I'm sure it can be done, I just don't know how (If anyone has a link or idea please share it.) But because I do like to compare things I tweaked the code to run within python 3.3.0. The differences in time are so minimal that I'm not even going to post it. If you're really inspired you can read the python 3 code here.

Questions and comments welcomed. One quick side note to my readers: I'm getting married this year (Yay!) and a lot of my free time is spent juggling and planning. So I might not be blogging as frequently as usual. Thanks for your patience.

As everyone should know by now, I love coding challenges. A while ago I came across this one, which is rather long:
`Using python with gevent 0.13.x and your choice of additional libraries and/or frameworks, implement a single HTTP server with API endpoints that provide the following functionalities:`

``` A Fibonacci endpoint that accepts a number and returns the Fibonacci calculation for that number, and returns result in JSON format. example: \$ curl -s 'http://127.0.0.1:8080/fib/13'{"response": 233} \$ curl -s 'http://127.0.0.1:8080/fib/12'{"response": 144} An endpoint that fetches the Google homepage and returns the sha1 of the response message-body (HTTP body data).example: \$ curl -s 'http://127.0.0.1:8080/google-body'{"response": "272cca559ffe719d20ac90adb9fc4e5716479e96"} Using some external storage of your choice (can be redis, memcache, sqlite, mysql, etc), provide a means to store and then retrieve a value.Example: \$ curl -d 'value=something' 'http://127.0.0.1:8080/store'\$ curl 'http://127.0.0.1:8080/store'{"response": "something"}</li> ```

At one point in my past a coworker talked about his love of the Flask micro framework. Since this is just a simple web API, I figured I'd give it a shot. This is a bit of a complicated task with many pieces, so let's set a game plan for the rest of this post. I'm going to share the specific functions related to each piece of functionality, then at the very end I will share the entire code base so everyone can see how it all fits together. One last note - to test out the run, you need to call the run.py script, which will also be included below. Ready … BREAK!

Let's tackle the google-body endpoint first:

`@app.route('/google-body')def google_body():    try:        sh = sha.new(urlopen('http://www.google.com').read())        return jsonify({'response' : sh.hexdigest()})    except Exception as e:        return jsonify({'response' : 'ERROR: %s' % str(e)})`

While this code block is very compact, it's not difficult to understand. Go out to the internet, get the source code for google's home page and insert that into the sha object. Wrap up the hexdigest results into a dictionary object, throw that into the jsonify function, and send it on its way. Don't forget to package it all in a nice try/except block for safety.

Onto the Fibonacci API call:

`@app.route('/fib/<number>')def fib(number):    try:        return jsonify({'response' : real_fib(int(number))})    except ValueError:        return jsonify({'response' : 'ERROR: Input not a number'}) @lru_cache()def real_fib(n):    """        This code was modified from the fib code in the python3 functools         documentation.    """    if n < 2:        return n    return real_fib(n-1) + real_fib(n-2)`

During PyCon US 2012, I became aware of the lru_cache decorator in python3.3. I also learned that Raymond Hettinger wrote code that would allow it work in python2, which allowed me to copy the code from the python3 documentation with little modification. Knowing about the lru_cache allowed me to write a nice and concise Fibonacci function reminiscent of something I might write in Haskell or some other functional language.

Now the last part of this challenge, and the longest. Before we get to the python, I feel that it might help your understanding if you know what kind of database schema we're working with. So I'm going to post that first, then the python code.

`drop table if exists entries;create table entries (    id integer primary key autoincrement,    value string not null);`

`@app.route('/store', methods=['GET', 'POST'])def store():    if request.method == 'POST':        try:            g.db.execute('insert into entries (value) values (?)',                         [request.form['value']])            g.db.commit()            resp = jsonify()            resp.status_code = 200            return resp        except Exception as e:            return jsonify({"response" : "ERROR: %s" % str(e)})    else:        try:            cur = g.db.execute('select value from entries order by id desc')            #fetchone returns a list. To better meet the requirements,            #just slicing the head of the list and output that.            return jsonify({'response' : cur.fetchone()[0]})        except IndexError:            return jsonify({'response' : 'NOTHING IN THE DATABASE'})`

This step is obviously a little more complex - the function has to process both the GET and the POST HTTP methods, while using an outside database to store and retrieve the information. I believe the code here is simple enough for you to understand, so I won't explain every line. For the POST method I had to do some juggling to get the desired return results. In the example above a POST method works, but does not receive an actual response. I was able to create this by using the jsonify object to create an empty Flask.Response object, and then set the status code of that response.

At the end of the day I'm pretty happy with this. It wasn't a hard challenge, but certainly allowed me to learn a bit about Flask. If I did over again, I might improve things by creating my own decorator to abstract all the try/except blocks. The errors would have to become more generic and maybe less helpful, but that is a worthwhile cost for being able to live the “Don't Repeat Yourself” mentality. The decorator would look something like this (the code below has not been tested - caveat emptor):

`def try_block(f):    @wraps    def wrapper(*args, **kwds):        try:            return f(*args,**kwds)       except ValueError:            return jsonify({'response' : 'ERROR: Input not a number'})`

As more functions start to use this decorator it'll most likely get uglier as it has to juggle more and more exceptions. While that is certainly a cost of having all of the error checking wrapped up in one location, the benefit that I can see is if another programmer were to add a new piece of functionality, he would know exactly where to go to add in the exceptions if it wasn't there already.

`@app.route('/fib/<number>')@try_blockdef fib(number):    return jsonify({'response' : real_fib(int(number))})`

I think this would clean up the function quite a bit.

Next time I'm going to show how to do this in Haskell using the Yesod web framework. As always, questions, and comments are welcomed.

run.py

`from gevent.wsgi import WSGIServerfrom playhaven import app, init_db init_db()http_server = WSGIServer(('0.0.0.0', 8080), app)http_server.serve_forever()`

challenge.py

`from __future__ import with_statementfrom urllib2 import urlopenfrom contextlib import closingfrom flask import Flask, request, g, jsonifyfrom lru_cache import lru_cacheimport sqlite3import sha DATABASE = '/tmp/challenge.db'DEBUG = TrueSECRET_KEY = 'c29tZXRoaW5nY2xldmVyaGVyZQ==\n'USERNAME = 'challenge'PASSWORD = 'chang3m3' app = Flask(__name__)app.config.from_object(__name__) app.config.from_envvar('CHALLENGE_SETTINGS', silent=True) def connect_db():    return sqlite3.connect(app.config['DATABASE']) def init_db():    with closing(connect_db()) as db:        with app.open_resource('schema.sql') as f:            db.cursor().executescript(f.read())        db.commit() @app.before_requestdef before_request():    g.db = connect_db() @app.teardown_requestdef teardown_request(exception):    g.db.close() @app.route('/fib/<number>')def fib(number):    try:        return jsonify({'response' : real_fib(int(number))})    except ValueError:        return jsonify({'response' : 'ERROR: Input not a number'}) @lru_cache()def real_fib(n):    """        This code was modified from the fib code in the python3 functools         documentation.    """    if n < 2:        return n    return real_fib(n-1) + real_fib(n-2) @app.route('/google-body')def google_body():    try:        sh = sha.new(urlopen('http://www.google.com').read())        return jsonify({'response' : sh.hexdigest()})    except Exception as e:        return jsonify({'response' : 'ERROR: %s' % str(e)}) @app.route('/store', methods=['GET', 'POST'])def store():    if request.method == 'POST':        try:            g.db.execute('insert into entries (value) values (?)',                         [request.form['value']])            g.db.commit()            resp = jsonify()            resp.status_code = 200            return resp        except Exception as e:            return jsonify({"response" : "ERROR: %s" % str(e)})    else:        try:            cur = g.db.execute('select value from entries order by id desc')            #fetchone returns a list. To better meet the requirements,            #just slicing the head of the list and output that.            return jsonify({'response' : cur.fetchone()[0]})        except IndexError:            return jsonify({'response' : 'NOTHING IN THE DATABASE'}) if __name__ == '__main__':    app.run()`

## Project Euler: Problem 16

I'm not dead yet! I've just been insanely busy the last month or two with changing jobs and preparing my first programming presentation for BayPiggies and Silicon Valley Code Camp (which is a post for the near future). Both of these have kept me away from my blog. Let me make it up to you with a solution to project Euler problem #16.

The challenge is:

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?

`#!/usr/bin/python print sum([int(i) for i in str(2 ** 1000)])`

For this solution, using a more functional approach definitely reduced the code base. But one thing I was a little surprised about is that having a list comprehension within the sum function is actually faster than a generator expression. Usually one hears how generator expressions are preferred over list comprehensions because they are more efficient with memory, among other reasons. However, it's actually faster to give sum a list. One quick caveat, this whole sum and list comprehension thing applies to Python 2. The same seems to be also be true for Python 3, at least from the interpreter:

`>>> import timeit>>> timeit.timeit("sum(int(x) for x in str(2 ** 1000))", number=1000)0.11109958100132644>>> timeit.timeit("sum([int(x) for x in str(2 ** 1000)])", number=1000)0.09597363900684286>>> timeit.timeit("sum(int(x) for x in str(2 ** 1000))", number=10000)1.051396899012616>>> timeit.timeit("sum([int(x) for x in str(2 ** 1000)])", number=10000)0.9054670640034601>>> timeit.timeit("sum(int(x) for x in str(2 ** 1000))", number=100000)10.498383879996254>>> timeit.timeit("sum([int(x) for x in str(2 ** 1000)])", number=100000)8.992312036993098`

`module Main where import Data.Char main :: IO ()main = print . sum . map digitToInt . show \$ 2 ^ 1000`

Maybe it's just me and my Haskell/Python-centric brain, but I think the algorithm is simple enough to easily see the similarities and differences between the two languages. If I wanted to write the Haskell code to better match the Python code (syntactic differences aside), it would look like this: (inside the Haskell interpreter)

`Prelude Data.Char> print . sum \$ [ digitToInt x | x <- show (2 ^ 1000)]`

Even though this code may be easier to read for a Python programmer, it's not “good” Haskell code. It'll get the job done, but the map is obfuscated by the list comprehension. We can also adjust the Python code to make it resemble Haskell by using map:

`print sum(map(int, str(2 ** 1000)))`

But that might get you “dinged” because some people think that using map is “too functional” or “not Pythonic”, even if the code might be faster. I don't subscribe to that line of thinking...but that's a discussion for another time.

Times:
python – list comprehension : .032s
python – map : .030s
haskell – list ( interpreted) : .155s
haskell – map (interpreted) : .155s
haskell – list (compiled) : .006s
haskell – map (compiled) : .006s

As always, questions, comments, and complaints are encouraged. I hope everyone will forgive me for not posting for so long... sometimes life happens.

## Project Euler: Problem 14

“The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd).  Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1.  It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.  Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.  Which starting number, under one million, produces the longest chain?  NOTE: Once the chain starts the terms are allowed to go above one million.”

Not many of you may be aware of this, but about a year ago I wrote up a blog post that discussed Collatz chains in Haskell.  You can find that post here: . Having some of the code already written made coming up with the solution easier.  However, just because I had one function doesn't mean I had the whole problem licked.  I still had a fair amount of work in front of me.  Below is my code from the first attempt at a solution:

`module Main where  import Data.List chain' :: Integer -> [Integer]chain' 1 = [1]chain' n    | n <= 0 = []    | even n = n : chain' (n `div` 2)    | odd n = n : chain' (n * 3 + 1)  main :: IO () main = do     let seqx = map chain' [3..1000000]     let lengthx = map length seqx     print . maximum \$ zip lengthx seqx`

This code appears to be logically correct but was incredibly slow - so slow that after over 2 minutes it still hadn’t completed.  I admit I can be a little impatient with these things from time to time, but in this case something was obviously wrong.

I devised two optimizations:

• Reverse the order of the list. I will be more likely to find the number with the longest chain near 1,000,000 than 3.
• Use odd numbers only. This is based on the fact that in the chain' function an odd number gets multiplied right off the bat, whereas an even number is instantly divided by 2, and also on the assumption that a higher number will be more likely to have a longer chain.  (I admit this was a complete experiment - I had no proof that it would work ahead of time, and knew it gave me the right answer only after the fact.)

The code then morphed into:

`module Main where  import Data.List chain' :: Integer -> [Integer]chain' 1 = [1]chain' n    | n <= 0 = []    | even n = n : chain' (n `div` 2)    | odd n = n : chain' (n * 3 + 1)  main :: IO () main = do     let seqx = map chain' [999999,999997..3]     let lengthx = map length seqx     print . maximum \$ zip lengthx seqx`

The problem I ran into with this code was that I received stack overflow errors; my list of tuples holding another long list of int’s was taking up to much memory.  I fixed this problem by computing the length of the list immediately after generating it.  The new code looked like this:

`import Data.List chain' :: Integer -> [Integer]chain' 1 = [1]chain' n    | n <= 0 = []    | even n = n : chain' (n `div` 2)    | odd n = n : chain' (n * 3 + 1)  main :: IO () main = do     let seqx = map (\x → (x, length \$ chain' x) [999999,999997..3]     print . maximum \$ seqx`

This got me a result within the one minute time frame, but it still wasn't the right answer.  Can you figure out why?  Using the great code Jedai posted in the comments of my Apache log post, I was able to get my answer and finally complete the problem:

`module Main where                                                                                 import Data.Tuple  import Data.List (sortBy)  import Data.Function (on)    chain' :: Integer -> [Integer]  chain' 1 = [1]  chain' n    | n <= 0 = []    | even n = n : chain' (n `div` 2)    | odd n = n : chain' (n * 3 + 1)    main :: IO ()  main = do      let seqx = map (\x -> (x, length \$ chain' x)) [999999,999997..3]      print . fst . head \$ sortBy (flip compare `on` snd) seqx`

After figuring that out, getting the python answer was a breeze:

`#!/usr/bin/python"""Python solution for Project Euler problem #14.""" from itertools import imap def sequence(number):    t_num = number    count = 1     while(t_num > 1):        if t_num % 2 == 0:            t_num /= 2        else:            t_num = (t_num * 3) + 1         count += 1     return (count, number) if __name__ == "__main__":  print max(imap(sequence, xrange(999999,3,-2)))`

Here are the speed numbers:
Python : 18.537s
`module Main where  import Data.Tuple import Data.List (sortBy, iterate) import Data.Function (on)  chain' :: Integer -> Int chain' n       | n < 1 = 0     | otherwise = 1 + (length \$ (takeWhile ( > 1) \$ iterate (\x -> if even x then x `div` 2 else x * 3 + 1) n))  main :: IO () main = do     let seqx = map (\x -> (x, chain' x)) [999999,999997..3]     print . fst . head \$ sortBy (flip compare `on` snd) seqx`