Project Euler Solutions

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):
		return (int(int(multiple) % int(integer)))
		print 'error for multiple %s and integer %s' % (multiple, integer)
		print 'error was', sys.exc_info()[0]
sum = 0
for multiple in range (1, 1000):
		if multipleof (multiple, 3) == 0 or multipleof (multiple, 5) == 0:
			sum += multiple
print 'The sum is ', sum

4 Responses to Project Euler Solutions

  1. moshez says:

    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)

  2. hs says:

    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?

  3. 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

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

  4. Hans Klein says:

    @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.

%d bloggers like this: