Writing my solution for Problem #1 in Python wasn't too difficult. The biggest problem with my new languages is mostly an issue of getting the command-line program working. In Haskell, this meant learning the IO monad stuff which wasn't in the language when I first used it. In Prolog, it was the same story, except that Prolog wasn't as worried about data types as Haskell.
But I found handling the command-line arguments and output in Python pretty easy to figure out.
Python Solution
def sum35(n):
return sum([m for m in range(0, n+1) if interestingNumber(m)])
def interestingNumber(n):
return n % 3 == 0 or n % 5 == 0
I have a feeling the indentation requirements of Python will end up bugging me. I had a few encounters with it already.
interestingNumber is easy enough. I found it odd to have to write return explicitly. I found it odd that I found this odd, too! But it occurs to me that all of my other languages (so far) don't require an explicit return. (For what it's worth, I've found myself leaving out my returns in my Java code for another project I'm working on.)
For sum35, I went with another list comprehension. I don't think I like this version as much as the Haskell version. Python's is expressive and terse, and a good Python interpreter could optimize it well, I'm sure. It just reads a bit awkward (i.e., it doesn't look like what I'd find in a mathematics book).

4 comments:
Hi,
I believe you can remove the matching square brackets in sum(...) to use a generator comprehension rather than a list comprehension. This will sum the elements without creating an intermediate list.
- Paddy.
Heres two other ways of doing the computation:
>>> sum(set(range(3,1000,3)) | set(range(5,1000,5)))
233168
>>> sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0)
233168
>>>
- Paddy.
Note, you gave the problem in your earlier post as
"
Add all the natural numbers below one thousand that are multiples of 3 or 5.
"
You use range(0,n+1) in your function so for the original problem you will need to call
sum35(999)
- Paddy.
@paddy3118: thanks for the alternatives! I'm going to have to read more about Python's generator comprehensions. I'm not sure if I like the solutions using set() or not, but it's good to see it as an alternative.
I'm going to address the n+1 issue in a future blog entry.
Post a Comment