473,396 Members | 1,743 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Little novice program written in Python

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,

--
Rogério Brito : rbrito@{mackenzie,ime.usp}.br : GPG key 1024D/7C2CAEB8
http://www.ime.usp.br/~rbrito : http://meusite.mackenzie.com.br/rbrito
Projects: algorithms.berlios.de : lame.sf.net : vrms.alioth.debian.org
Jun 27 '08 #1
21 1364
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):
It looks like straight-forward code and is fine as it stands.
If you want to tweak it a bit, you can avoid using a flag like
"finished" by using a break-statement.
Raymond
Jun 27 '08 #2
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/

Jun 27 '08 #3
On Apr 24, 11:09*pm, Dennis Lee Bieber <wlfr...@ix.netcom.comwrote:
On Thu, 24 Apr 2008 21:31:15 -0300, Rogério Brito <rbr...@ime.usp.br>
declaimed the following in comp.lang.python:
a = [i for i in range(0,n+1)]

* * * * Uhm... At least in 2.4 and earlier, range() returns a list.... No
need for the list-comp in that era... range() also begins with 0
>n = 5
a = range(n+1)
a
[0, 1, 2, 3, 4, 5]

* * * * So just

* * * * a = range(n+1)

could be used. Of course, if using a version where range() and xrange()
have been unified...
>c = list(xrange(n+1))
c
[0, 1, 2, 3, 4, 5]

--
* * * * Wulfraed * * * *Dennis Lee Bieber * * * * * * * KD6MOG
* * * * wlfr...@ix.netcom.com * * * * * * *wulfr...@bestiaria.com
* * * * * * * * HTTP://wlfraed.home.netcom.com/
* * * * (Bestiaria Support Staff: * * * * * * * web-a...@bestiaria.com)
* * * * * * * * HTTP://www.bestiaria.com/
You're talking hardware-native, which machines don't guarantee.
Python can in another dimension of machine compatibility. Stacks are
hardware native, the location of an array is not. Python can retrieve
your stack in higher dimensions.

Fortunately, Python's community is sturdy against counterproductivity
en masse, so it's okay to hairbrain it. Cover features of
improvements, though, and you might get a Bayes Net change to make and
courses to steer. The community values the flexibility of machine-
independency too.

However, real numbers are not integers, so opinion mass of integer
algorithms may favor C. But you just need micro-sales (and scales!)
to examine the future of Python. Welcome to our group.
Jun 27 '08 #4
Rogério Brito wrote:
i = 2
while i <= n:
Â* Â* Â*if a[i] != 0:
Â*Â*Â*Â*Â*Â*Â*Â*print a[i]
Â* Â* Â*i += 1
You can spell this as a for-loop:

for p in a:
if p:
print p

It isn't exactly equivalent, but gives the same output as we know that a[0]
and a[1] are also 0.

Peter
Jun 27 '08 #5
Peter Otten wrote:
Rogério Brito wrote:

>i = 2
while i <= n:
if a[i] != 0:
print a[i]
i += 1

You can spell this as a for-loop:

for p in a:
if p:
print p

It isn't exactly equivalent, but gives the same output as we know that a[0]
and a[1] are also 0.
If the OP insists in not examining a[0] and a[1], this will do exactly
the same as the while version:

for p in a[2:]:
if p:
print p
Cheers,
RB
Jun 27 '08 #6
On Apr 25, 5:44 pm, Robert Bossy <Robert.Bo...@jouy.inra.frwrote:
Peter Otten wrote:
Rogério Brito wrote:
i = 2
while i <= n:
if a[i] != 0:
print a[i]
i += 1
You can spell this as a for-loop:
for p in a:
if p:
print p
It isn't exactly equivalent, but gives the same output as we know that a[0]
and a[1] are also 0.

If the OP insists in not examining a[0] and a[1], this will do exactly
the same as the while version:

for p in a[2:]:
if p:
print p
... at the cost of almost doubling the amount of memory required.
Jun 27 '08 #7
John Machin wrote:
On Apr 25, 5:44 pm, Robert Bossy <Robert.Bo...@jouy.inra.frwrote:
>Peter Otten wrote:
>>Rogério Brito wrote:

i = 2
while i <= n:
if a[i] != 0:
print a[i]
i += 1

You can spell this as a for-loop:

for p in a:
if p:
print p

It isn't exactly equivalent, but gives the same output as we know that a[0]
and a[1] are also 0.
If the OP insists in not examining a[0] and a[1], this will do exactly
the same as the while version:

for p in a[2:]:
if p:
print p


... at the cost of almost doubling the amount of memory required.
Indeed. Would it be a sensible proposal that sequence slices should
return an iterator instead of a list?

RB
Jun 27 '08 #8


Rogério Brito:
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):
my variant of the sieve

def GetPrimes(N):
arr = []
for i in range(1,N+1):
arr.append(i)
#Set first item to 0, because 1 is not a prime
arr[0]=0
#sieve processing
s=2
while s < math.sqrt(N):
if arr[s-1] != 0:
j = s*s
while j <= N:
arr[j-1] = 0
j += s
s += 1
return [x for x in arr if x != 0]
Jun 27 '08 #9
also, i would recommend you to visit projecteuler.net
you can solve math tasks and then see how others have done the same.

you can fetch very good and pythonic solution there.

Jun 27 '08 #10
hellt <Do*********@gmail.comwrites:
my variant of the sieve
Since you posted it, you are also looking for advice to improve your
code ;)
def GetPrimes(N):
arr = []
for i in range(1,N+1):
arr.append(i)
This is the same as:
arr = range(1, N+1)
!-)
#Set first item to 0, because 1 is not a prime
arr[0]=0
#sieve processing
s=2
remove this line
while s < math.sqrt(N):
for s in xrange(2, int(math.sqrt(N))+1):
if arr[s-1] != 0:
if arr[s-1]:
j = s*s
remove this line
while j <= N:
for j in xrange(s*s, N+1, s):
arr[j-1] = 0
j += s
remove this line
s += 1
remove this line
return [x for x in arr if x != 0]
return filter(None, arr)
Altogether now:

def getprimes(N):
arr = range(1, N+1)
arr[0] = 0
for s in xrange(2, int(math.sqrt(N))+1):
if arr[s-1]:
for j in xrange(s*s, N+1, s):
arr[j-1] = 0
return filter(None, arr)

It's the same, but it looks a bit less like the litteral translation
of some C code.
Lastly, the lines:

for j in xrange(s*s, N+1, s):
arr[j-1] = 0

from above can be condensed using extended slices:

arr[s*s-1 : N+1 : s] = [0] * (N/s - s + 1)

(If I can count correctly)

Giving the following, slightly shorter and probably faster:

def getprimes(N):
arr = range(1, N+1)
arr[0] = 0
for s in xrange(2, int(math.sqrt(N))+1):
if arr[s-1]:
arr[s*s-1 : N+1 : s] = [0] * (N/s - s + 1)
return filter(None, arr)
If it was me, I would include 0 in the array, giving the slightly simpler:

def getprimes(N):
arr = range(N+1)
arr[1] = 0
for s in xrange(2, int(math.sqrt(N))+1):
if arr[s]:
arr[s*s : N+1 : s] = [0] * (N/s - s + 1)
return filter(None, arr)

(I think)

This all needs to be tested.

--
Arnaud
Jun 27 '08 #11
On 25 ÁÐÒ, 13:29, Arnaud Delobelle <arno...@googlemail.comwrote:
hellt <Dodin.Ro...@gmail.comwrites:
my variant of the sieve

Since you posted it, you are also looking for advice to improve your
code ;)
def GetPrimes(N):
arr = []
for i in range(1,N+1):
arr.append(i)

This is the same as:
arr = range(1, N+1)
!-)
#Set first item to 0, because 1 is not a prime
arr[0]=0
#sieve processing
s=2

remove this line
while s < math.sqrt(N):

for s in xrange(2, int(math.sqrt(N))+1):
if arr[s-1] != 0:

if arr[s-1]:
j = s*s

remove this line
while j <= N:

for j in xrange(s*s, N+1, s):
arr[j-1] = 0
j += s

remove this line
s += 1

remove this line
return [x for x in arr if x != 0]

return filter(None, arr)

Altogether now:

def getprimes(N):
arr = range(1, N+1)
arr[0] = 0
for s in xrange(2, int(math.sqrt(N))+1):
if arr[s-1]:
for j in xrange(s*s, N+1, s):
arr[j-1] = 0
return filter(None, arr)

It's the same, but it looks a bit less like the litteral translation
of some C code.

Lastly, the lines:

for j in xrange(s*s, N+1, s):
arr[j-1] = 0

from above can be condensed using extended slices:

arr[s*s-1 : N+1 : s] = [0] * (N/s - s + 1)

(If I can count correctly)

Giving the following, slightly shorter and probably faster:

def getprimes(N):
arr = range(1, N+1)
arr[0] = 0
for s in xrange(2, int(math.sqrt(N))+1):
if arr[s-1]:
arr[s*s-1 : N+1 : s] = [0] * (N/s - s + 1)
return filter(None, arr)

If it was me, I would include 0 in the array, giving the slightly simpler:

def getprimes(N):
arr = range(N+1)
arr[1] = 0
for s in xrange(2, int(math.sqrt(N))+1):
if arr[s]:
arr[s*s : N+1 : s] = [0] * (N/s - s + 1)
return filter(None, arr)

(I think)

This all needs to be tested.

--
Arnaud
nice, but i'm a newbie to python too, so some things for me seems a
liitle complicated)))
Jun 27 '08 #12
On Fri, 25 Apr 2008 10:24:16 +0200, Robert Bossy wrote:
John Machin wrote:
>On Apr 25, 5:44 pm, Robert Bossy <Robert.Bo...@jouy.inra.frwrote:
>>Peter Otten wrote:
If the OP insists in not examining a[0] and a[1], this will do exactly
the same as the while version:

for p in a[2:]:
if p:
print p


... at the cost of almost doubling the amount of memory required.
Indeed. Would it be a sensible proposal that sequence slices should
return an iterator instead of a list?
I don't think so as that would break tons of code that relies on the
current behavior. Take a look at `itertools.islice()` if you want/need
an iterator.

Ciao,
Marc 'BlackJack' Rintsch
Jun 27 '08 #13
Rogério Brito skrev:
Hi, All.

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):

I agree with the rest here. Your code generally looks fine.

But on another note, this type of code is not something you often see in
Python. It is very dense with regard to algorithm.

Most code is not like that so perhaps you should try something more
"usual" like sending email, fetching webpages etc. to get a feel for the
language.
--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Jun 27 '08 #14
On 25 §Ñ§á§â, 15:02, Max M <m...@mxm.dkwrote:
Rog¨¦rio Brito skrev:
Hi, All.
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):

I agree with the rest here. Your code generally looks fine.

But on another note, this type of code is not something you often see in
Python. It is very dense with regard to algorithm.

Most code is not like that so perhaps you should try something more
"usual" like sending email, fetching webpages etc. to get a feel for the
language.

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
em, i would say, that python (esp. with NumPy+Psyco) is very popular
in numerical processing also.
Jun 27 '08 #15
Rogério Brito <rb****@ime.usp.brwrote:
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).
When you are up to speed in python I suggest you check out gmpy for
number theory algorithms.

Eg :-

import gmpy
p = 2
while 1:
print p
p = gmpy.next_prime(p)

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jun 27 '08 #16
hellt skrev:
>Most code is not like that so perhaps you should try something more
"usual" like sending email, fetching webpages etc. to get a feel for the
language.
em, i would say, that python (esp. with NumPy+Psyco) is very popular
in numerical processing also.
I know, and I might be way of, but I would believe that even that would
be more like stringing ready built modules together, calling methods etc.

I have written far denser code that the above example in Python
regularly. But It is like 1%-5% of my code I believe.

Unlike the c family of languages where there is a lot more algorithms
due to the low level coding. Memory handling, list, dicts etc. qickly
becomes more like math algorithms than in Python.
--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Jun 27 '08 #17
Marc 'BlackJack' Rintsch wrote:
>Indeed. Would it be a sensible proposal that sequence slices should
return an iterator instead of a list?

I don't think so as that would break tons of code that relies on the
current behavior. Take a look at `itertools.islice()` if you want/need
an iterator.
A pity, imvho. Though I can live with islice() even if it is not as
powerful as the [:] notation.

RB
Jun 27 '08 #18
On 04/25/2008 01:09 AM, Dennis Lee Bieber wrote:
On Thu, 24 Apr 2008 21:31:15 -0300, Rogério Brito <rb****@ime.usp.br>
declaimed the following in comp.lang.python:
>a = [i for i in range(0,n+1)]

Uhm... At least in 2.4 and earlier, range() returns a list... No
need for the list-comp in that era... range() also begins with 0
Thanks for the suggestion. As I stated in my original message, I'm only
"side-learning" Python, and I naturally think in list-comprehensions (it is like
a set in Mathematics and you've seen that my program is Mathematical in its nature).

This is exactly the kind of suggestion that I was looking for.
Thanks, Rogério.

--
Rogério Brito : rbrito@{mackenzie,ime.usp}.br : GPG key 1024D/7C2CAEB8
http://www.ime.usp.br/~rbrito : http://meusite.mackenzie.com.br/rbrito
Projects: algorithms.berlios.de : lame.sf.net : vrms.alioth.debian.org
Jun 27 '08 #19
On 04/25/2008 01:30 AM, Steve Holden wrote:
Rogério Brito wrote:
>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).
Your Python is actually pretty good - if Raymond Hettinger pronounces it
OK then few would dare to disagree.
Thank you.
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.
I didn't know about the pejorative meaning of Pythonesque. :-) Thanks for the
comment on my English (which should be obvious that I'm not a native speaker).
PS: I think either my mailer or yours has mangled the indentation.
I think that it was mine.
Thanks, Rogério Brito.

--
Rogério Brito : rbrito@{mackenzie,ime.usp}.br : GPG key 1024D/7C2CAEB8
http://www.ime.usp.br/~rbrito : http://meusite.mackenzie.com.br/rbrito
Projects: algorithms.berlios.de : lame.sf.net : vrms.alioth.debian.org
Jun 27 '08 #20
On 04/25/2008 05:00 AM, John Machin wrote:
On Apr 25, 5:44 pm, Robert Bossy <Robert.Bo...@jouy.inra.frwrote:
>If the OP insists in not examining a[0] and a[1], this will do exactly
the same as the while version:

for p in a[2:]:
if p:
print p

... at the cost of almost doubling the amount of memory required.
Yes, despite the asymptotic consumption of memory being the same, the practical
one is also a concern. And in my original version of that loop (sketched in
paper) was a for loop, but with C syntax.

--
Rogério Brito : rbrito@{mackenzie,ime.usp}.br : GPG key 1024D/7C2CAEB8
http://www.ime.usp.br/~rbrito : http://meusite.mackenzie.com.br/rbrito
Projects: algorithms.berlios.de : lame.sf.net : vrms.alioth.debian.org
Jun 27 '08 #21
On 04/25/2008 09:30 AM, Nick Craig-Wood wrote:
When you are up to speed in python I suggest you check out gmpy for
number theory algorithms.
Thanks. That is quite useful to know when I don't want to code explicitly the
details of the algorithm.
Thanks, Rogério.

--
Rogério Brito : rbrito@{mackenzie,ime.usp}.br : GPG key 1024D/7C2CAEB8
http://www.ime.usp.br/~rbrito : http://meusite.mackenzie.com.br/rbrito
Projects: algorithms.berlios.de : lame.sf.net : vrms.alioth.debian.org
Jun 27 '08 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Ron Stephens | last post by:
I posted to my web site a fun little program called merlin.py today. Please keep in mind that I am a hobbyist and this is just a little hack, if you look at the code you will see that it is still...
76
by: Alan Connor | last post by:
-- Alan C this post ends with w q From K&R: #include <stdio.h> main()
2
by: bole2cant | last post by:
I just received my free VB.NET package from MS, and can't figure out how to Save As. I loaded a sample program and made a bunch of changes to it and wanted to save it without overwriting the...
4
by: vagrantbrad | last post by:
I'm using python 2.4 running on Fedora Core 4. I have written a python program called ipscan.py that checks the external ip address of my cable internet connection, and on change, will update the...
1
by: The Confessor | last post by:
For my previous project, I stored persistent data from Structures in three different Random Access files between sessions, but that's not likely to be an option with this one... For starters,...
29
by: 63q2o4i02 | last post by:
Hi, I'm interested in using python to start writing a CAD program for electrical design. I just got done reading Steven Rubin's book, I've used "real" EDA tools, and I have an MSEE, so I know what...
3
by: Darius | last post by:
Hello, there is an NMEAParserDemo application written in VC++ avaliable for download from http://www.visualgps.net/Papers/NMEAParser/NMEAParserDemo%20Project.zip. Source code in VC++ is...
4
by: Chelonian | last post by:
I'm considering trying to learn Python for a specific reason, and hoped the group might help me get a sense for whether it would be worth my time. The situation... Me: total beginner w/ a...
1
by: TwistedSpanner | last post by:
Hello all, For the record I am a complete java novice. I have to write a program to generate/output to screen 10 simple maths question and output a final score . The question is as follows ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.