### Functional Programming and Python

After reading about functional programming in Python, I attempted to solve problem 48 of Project Euler with some of its techniques. I tried something like

`print(reduce(lambda x, y: y**y , range(1,1000)))`

to get the inhumanely large number that is 1 to the power of 1, added to 2 to the power of 2, added to 3 to the power of 3, up to 1000 to the power of 1000. Unfortunately I don’t think I fully understand what reduce does; it only ends up calculating 1000^1000. And that line doesn’t trim away all but the last ten digits of the number, which is required for the solution.

In the end I just did this:

`total = 0`

for r in range(1,1001):

total = total+r**r

print(str(total)[-10:])

(Urgh, python code indenting doesn’t show up well here. I’ll probably have to find another way of showing code in the future.)

I had a lambda function earlier, but then I realised it was easier to simply do the ** expression within the *for* interator. I am a little disappointed I was not able to use the new knowledge I learnt, but I suppose there is a better use for these techniques than this. And a better FP languages also exist, too.

Anyway, what else. I found some decent-looking documentation for Xlib while hunting for information on how to understand the source code for dwm. They are here and here.

Filed under: programming | 4 Comments

Tags: python

Reduce is the wrong tool for this particular job. What you want is something more like like

Hi,

You could have done:

str(sum(n**n for n in range(1,1+1000)))[-10:]

– Paddy.

Thank you both so much. Your solutions make me feel like an ant in the presence of giants…. 🙂

Hardly a giant 🙂

(You should have seen how inelegant my Fizz-Buzz solution was).