# Project Euler Solutions

December 20, 2007 4 Comments

Head to Project Euler to solve mathematical problems using programming. I am cheating. I should not post these solutions but I want to get feedback on the quality of solutions implemented. The results are correct but are they generated from “quality” code? Only by sharing the code can I and others know.

Why am I using Python? Because this way I can learn how to program in it. Plus I get to learn more math.

### Problem 1

`import sys def multipleof (multiple = 1, integer = 1): try: return`

`(int(int(multiple) % int(integer)))`

`except: print 'error for multiple %s and integer %s' % (multiple, integer) print 'error was', sys.exc_info()[0] raise sum = 0 for multiple in range (1, 1000): try: if multipleof (multiple, 3) == 0 or multipleof (multiple, 5) == 0: sum += multiple except: pass print 'The sum is ', sum`

Advertisements

Some comments:

* What’s with all the try/except? How does that improve your program at all? If there’s an exception you don’t know how to handle, don’t handle it. Python will happily print out a good stack trace.

* Given the above, multipleof is redundant. In the case of your program, it is equivalent completely to “x%y”, with a lot of extra casts to integers which are no-ops. Redundant “future proofing” which it probably isn’t anyway.

* Why not use the “sum” function? It does sums better…

So I would replace the whole program above with the elegant one line of

sum([x for x in range(1,1000) if x%3==0 or x%5==0])

Exercise: what is redundant now? (I am counting at least two characters, left over from copying part of the original program)

That was a very good lesson. I am moving from C (at which I wasn’t very good either) and am still unaware of different ways to write code. I didn’t know about the ‘sum’ function and also didn’t realize that lists could be generated dynamically without storing them in variables. I also realize the mistake of “future proofing” without the need to do so. One of my goals was to learn how to write functions and how to handle exceptions. But for this problem it was overkill. Live and learn, eh?

I created an open source project for hosting solutions to the problems of project euler, using diff programming languages. The solutions can be found here

http://code.google.com/p/project-euler/

I believe the solution you posted here is very similar to the java solution I came up with

http://code.google.com/p/project-euler/source/browse/trunk/euler/src/com/google/code/projecteuler/Problem001.java

@Cesar Arevalo

Could you tell me what makes you think that pubishing solutions to Project Euler problems is a good idea? The problems are meant to be solved by the members themselves. Publishing solutions spoils that. Moreover if you’d read the pdf for problem 1 that is available you would have understood that your solution is a very naive one that can be much improved on.