Pythagoras and lambdas…..
Here is the first bit of code I’ve ever written at college (on my own computer though, I’ve concentration problems in the lab). I was solving problem 39 of the project euler problem set (and I am ashamed of my work). So the question is:
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
1000, is the number of solutions maximised?
So, I decided that I could look for Pythagorean triplets using the following snippet:
if c ** 2 == a ** 2 + b ** 2 and a + b + c < 1000:
return True
else:
return False
for c in xrange(1000):
for b in xrange(c):
for a in xrange(b+1):
if checkCond(a, b, c):
if peri_count.has_key(a+b+c):
peri_count[a+b+c] += 1
else:
peri_count[a+b+c] = 1
else:
continue
That gives us a dictionary whose (key, value) pairs are (perimeter, count). We need the max count and then pick the corresponding perimeter. I hence wrote a small function (which was very inefficient) to make the value the keys and the keys the values. I think it is the second time I used “lambda”:
”‘Flip the dictionary’s (key, value) pairs to (value, key)”‘
return dict(map(lambda item: (item[1], item[0]), dict_name.items()))
and finally, to complete the script:
max_no = max(peri_count.keys())
print peri_count[max_no]
So, here are the rather shameful execution stats:
$ time python euler39.py 840 real 3m15.140s user 0m0.046s sys 0m0.015s
I suggest you throw a glance at the awesome header that http://desk.stinkpot.org:8080/blog/ has.
Happy Coding.
About this entry
You’re currently reading “Pythagoras and lambdas…..,” an entry on Shriphani Palakodety
- Published:
- 08.23.08 / 10pm
- Category:
- Mathematics, python
7 Comments
Jump to comment form | comments rss [?] | trackback uri [?]