Little novice program written in Python
Steve Holden
steve at holdenweb.com
Fri Apr 25 00:30:02 EDT 2008
Rogério Brito wrote:
> Hi, All.
>
> I'm just getting my feet wet on Python and, just for starters, I'm
> coding some elementary number theory algorithms (yes, I know that most
> of them are already implemented as modules, but this is an exercise in
> learning the language idioms).
>
> As you can see from the code below, my background is in C, without too
> much sophistication.
>
> What I would like is to receive some criticism to my code to make it
> more Python'esque and, possibly, use the resources of the computer in a
> more efficient way (the algorithm implemented below is the Sieve of
> Eratosthenes):
>
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> #!/usr/bin/env python
>
> n = int(raw_input())
> a = [i for i in range(0,n+1)]
> a[1] = 0 # not a prime
> prime = 1 # last used prime
> finished = False
>
> while (not finished):
> prime = prime + 1
> # find new prime
> while prime*prime <= n and a[prime] == 0:
> prime += 1
> # cross the composite numbers
> if prime*prime <= n:
> j = 2*prime
> while j <= n:
> a[j] = 0
> j += prime
> else:
> finished = True
>
> # print out the prime numbers
> i = 2
> while i <= n:
> if a[i] != 0:
> print a[i]
> i += 1
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
>
> Thank you for any help in improving this program,
>
Your Python is actually pretty good - if Raymond Hettinger pronounces it
OK then few would dare to disagree.
As for your English, though, the word you sought was "Pythonic" (not
that you will ever find such a word in Webster's dictionary). To suggest
that your code is Pythonesque would mean you found it farcical or
ridiculous (like a Monty Python sketch), which it clearly is not.
Another wrinkle you might consider is simply printing the primes out as
they are generated rather than doing the printing in a separate loop,
though whether that approach would be preferable in "real life" would
depend on the application, of course.
regards
Steve
PS: I think either my mailer or yours has mangled the indentation.
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list