# Go deh!

Mainly Tech projects on Python and Electronic Design Automation.

## Sunday, November 11, 2012

### "How do I love thee? Let me count the ways..."

I was reading a post by CodeBuddy via reddit on brute force techniques in Python and it was getting a lot of grief in the reddit comments.

It turns out that the author was learning Python and blogging to help him remember. He wrote a lot but with very little meat so I guess the redditers were justified in one sense as they may have expected more, but as soon as I heard that the guy was learning Python I thought back to some small thing I did the week before that I think may interest both him and the redditers in providing a little (and only a little), more meat on the table.

So, I was on Youtube which now insists on giving me more of what I liked before and I got to watching an episode of Numberphile called "One to One Million" in which they posed the question:

"What is the sum of the digits of all the numbers one to one million"

Now, I new they would go on to give some fiendishly clever way of doing it (so clever it is simple). But I had my engineers hat on, and I quickly worked out that a brute-force direct approach in Python would not take long to write or run. Indeed, a few minutes later I had something like the following:

>>> x = ''.join(str(i) for i in range(1, 1000000+1))
>>> sum(int(digit) * x.count(digit) for digit in '123456789')
27000001
>>>

The Python code just concatenates all the string representations of all numbers in the range together, (that's only 5888896 digits); it then sums the digits by finding out how many of each there are multiplied by the digits value.

Not a brainy solution but I had time to pay attention to their solution which was to take numbers in pairs from the ...

... Best to watch the video.

P.s. In searching for the title I reacquainted myself with this poem by Elizabeth Barrett Browning:

How do I love thee? Let me count the ways.
I love thee to the depth and breadth and height
My soul can reach, when feeling out of sight
For the ends of being and ideal grace.
I love thee to the level of every day's
Most quiet need, by sun and candle-light.
I love thee freely, as men strive for right.
I love thee purely, as they turn from praise.
I love thee with the passion put to use
In my old griefs, and with my childhood's faith.
I love thee with a love I seemed to lose
With my lost saints. I love thee with the breath,
Smiles, tears, of all my life; and, if God choose,
I shall but love thee better after death.