473,804 Members | 2,100 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A dumb question about a class

I'm still trying to understand classes. I've made some progress, I
think, but I don't understand how to use this one. How do I call it,
or any of its functions? It's from the Cookbook, at
<http://aspn.activestat e.com/ASPN/Cookbook/Python/Recipe/523048>.

Thanks,

Dick Moores

=============== =============== =============== ========
class PrimeList:
def __init__(self, initial=0):
self.primelist = [2,3]
self.primelooku p = [0,0,1,1]
self.max_prime = 3
self.grow_prime list(initial)

def grow_primelist( self,number):
newprimes = []
while self.max_prime <= number:
next = self.nextprime( )
newprimes.appen d(next)
self.max_prime = next
size_difference = self.max_prime - len(self.primel ookup) + 1
self.primelooku p.extend([0] * size_difference )
for i in newprimes:
self.primelooku p[i]=1

def contains(self,n umber):
if number < 2:
return 0
if number len(self.primel ookup) - 1:
self.grow_prime list(number)
return self.primelooku p[number]
return self.primelooku p[number]

def nextprime(self) :
i = self.max_prime + 2
while 1:
isprime = True
for prime in self.primelist:
if i % prime == 0:
isprime = False
i += 2
break
if isprime:
self.primelist. append(i)
return(i)
=============== =============== =============== =========

Aug 12 '07 #1
10 1354
Dick Moores wrote:
I'm still trying to understand classes. I've made some progress, I
think, but I don't understand how to use this one. How do I call it, or
any of its functions? It's from the Cookbook, at
<http://aspn.activestat e.com/ASPN/Cookbook/Python/Recipe/523048>.
The short answer is that use should look something like::
>>plist = PrimeList()
plist.contain s(32)
False
>>plist.contain s(23)
True

But this doesn't seem like a particularly good recipe. Seems like you
would really rather be writing code like::
>>plist = PrimeList()
1 in plist
False
>>2 in plist
True
>>22 in plist
False
>>23 in plist
True
>>782 in plist
False
>>787 in plist
True

Here's how I'd write the recipe::

import itertools

def iter_primes():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count (2)

# generate primes forever
while True:

# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime

# remove all numbers from the (infinite) iterator that are
# divisible by the prime we just generated
numbers = itertools.ifilt er(prime.__rmod __, numbers)
class PrimeList(objec t):
def __init__(self):
# infinite iterator of primes
self._prime_ite r = iter_primes()

# the last prime we've seen
self._last_prim e = None

# all primes seen so far
self._prime_set = set()

# add the first prime (so that _last_prime is set)
self._add_prime ()

def __contains__(se lf, n):
# add primes to the list until we exceed n
while n self._last_prim e:
self._add_prime ()

# return True if n is one of our primes
return n in self._prime_set

def _add_prime(self ):
# take a prime off the iterator and update the prime set
self._last_prim e = self._prime_ite r.next()
self._prime_set .add(self._last _prime)
STeVe
Aug 12 '07 #2
At 03:09 PM 8/12/2007, Steven Bethard wrote:
>Here's how I'd write the recipe::

import itertools

def iter_primes():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count (2)

# generate primes forever
while True:

# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime

# remove all numbers from the (infinite) iterator that are
# divisible by the prime we just generated
numbers = itertools.ifilt er(prime.__rmod __, numbers)
class PrimeList(objec t):
def __init__(self):
# infinite iterator of primes
self._prime_ite r = iter_primes()

# the last prime we've seen
self._last_prim e = None

# all primes seen so far
self._prime_set = set()

# add the first prime (so that _last_prime is set)
self._add_prime ()

def __contains__(se lf, n):
# add primes to the list until we exceed n
while n self._last_prim e:
self._add_prime ()

# return True if n is one of our primes
return n in self._prime_set

def _add_prime(self ):
# take a prime off the iterator and update the prime set
self._last_prim e = self._prime_ite r.next()
self._prime_set .add(self._last _prime)
I'm afraid my next question is "How do I run this"?

Dick
Aug 12 '07 #3
Dick Moores wrote:
At 03:09 PM 8/12/2007, Steven Bethard wrote:
>Here's how I'd write the recipe::

import itertools

def iter_primes():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count (2)

# generate primes forever
while True:

# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime

# remove all numbers from the (infinite) iterator that are
# divisible by the prime we just generated
numbers = itertools.ifilt er(prime.__rmod __, numbers)
class PrimeList(objec t):
def __init__(self):
# infinite iterator of primes
self._prime_ite r = iter_primes()

# the last prime we've seen
self._last_prim e = None

# all primes seen so far
self._prime_set = set()

# add the first prime (so that _last_prime is set)
self._add_prime ()

def __contains__(se lf, n):
# add primes to the list until we exceed n
while n self._last_prim e:
self._add_prime ()

# return True if n is one of our primes
return n in self._prime_set

def _add_prime(self ):
# take a prime off the iterator and update the prime set
self._last_prim e = self._prime_ite r.next()
self._prime_set .add(self._last _prime)

I'm afraid my next question is "How do I run this"?

The same way I showed at the top (which you snipped in your reply)::
>>plist = PrimeList()
1 in plist
False
>>2 in plist
True
>>22 in plist
False
>>23 in plist
True
>>782 in plist
False
>>787 in plist
True

The first line, ``plist = PrimeList()`` creates a PrimeList object and
names it ``plist``. You can then check whether a prime is in that
PrimeList object much like you might check a normal ``list`` or ``set``
object -- using the ``in`` operator as above.

Note that if you just want to iterate over all the primes, there's no
need for the class at all. Simply write::

for prime in iter_primes():
...

HTH,

STeVe
Aug 12 '07 #4
At 03:35 PM 8/12/2007, Steven Bethard wrote:
>Note that if you just want to iterate over all the primes, there's no
need for the class at all. Simply write::

for prime in iter_primes():
Even if I want to test only 1 integer, or want the list of primes in
a certain interval, I don't need the class at all:

=============== =============== ======
import itertools

def iter_primes():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count (2)
# generate primes forever
while True:
# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime
# remove all numbers from the (infinite) iterator that are
# divisible by the prime we just generated
numbers = itertools.ifilt er(prime.__rmod __, numbers)

def listPrimes(n,m) :
"""
Returns the list of primes in closed interval [n,m]
"""
primes = []
for prime in iter_primes():
if prime m:
return primes
if n <= prime <= m:
primes.append(p rime)
=============== =============== ==============

Thanks for your help. I didn't learn much about classes, but
appreciated your iter_primes() a lot!

Dick Moores

Aug 13 '07 #5
On Aug 12, 5:09 pm, Steven Bethard <steven.beth... @gmail.comwrote :
def iter_primes():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count (2)

# generate primes forever
while True:

# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime

# remove all numbers from the (infinite) iterator that are
# divisible by the prime we just generated
numbers = itertools.ifilt er(prime.__rmod __, numbers)
This is kind of OT (from the thread), but in this iter_primes
function, numbers is becoming an ifilter of an ifilter of an ifilter
of an ifilter of an ifilter of an ifilter of... Is that really at all
efficient for larger numbers (millions or billions, or even bigger)?

Aug 13 '07 #6
On Aug 12, 7:35 pm, Dustan <DustanGro...@g mail.comwrote:
On Aug 12, 5:09 pm, Steven Bethard <steven.beth... @gmail.comwrote :
def iter_primes():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count (2)
# generate primes forever
while True:
# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime
# remove all numbers from the (infinite) iterator that are
# divisible by the prime we just generated
numbers = itertools.ifilt er(prime.__rmod __, numbers)

This is kind of OT (from the thread), but in this iter_primes
function, numbers is becoming an ifilter of an ifilter of an ifilter
of an ifilter of an ifilter of an ifilter of... Is that really at all
efficient for larger numbers (millions or billions, or even bigger)?
To word my question better:

How does this algorithm compare and contrast to maintaining a
dictionary or set and iterating through those structures to find out
if a number is divisible? All of those algorithms I've described are
O(n^2), if I'm not mistaken, but as far as memory-efficiency and the
likes, how do they compare/contrast?

Aug 13 '07 #7
Dustan wrote:
On Aug 12, 7:35 pm, Dustan <DustanGro...@g mail.comwrote:
>On Aug 12, 5:09 pm, Steven Bethard <steven.beth... @gmail.comwrote :
>> def iter_primes():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count (2)
# generate primes forever
while True:
# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime
# remove all numbers from the (infinite) iterator that are
# divisible by the prime we just generated
numbers = itertools.ifilt er(prime.__rmod __, numbers)
This is kind of OT (from the thread), but in this iter_primes
function, numbers is becoming an ifilter of an ifilter of an ifilter
of an ifilter of an ifilter of an ifilter of... Is that really at all
efficient for larger numbers (millions or billions, or even bigger)?

To word my question better:

How does this algorithm compare and contrast to maintaining a
dictionary or set and iterating through those structures to find out
if a number is divisible? All of those algorithms I've described are
O(n^2), if I'm not mistaken, but as far as memory-efficiency and the
likes, how do they compare/contrast?
I don't have the answer off hand, but if anyone wants to report some
timeit results or memory consumption here, I'd be interested.

STeVe
Aug 13 '07 #8
Dick Moores wrote:
At 03:35 PM 8/12/2007, Steven Bethard wrote:
>Note that if you just want to iterate over all the primes, there's no
need for the class at all. Simply write::

for prime in iter_primes():

Even if I want to test only 1 integer, or want the list of primes in a
certain interval, I don't need the class at all
Yep. That was the basis of my original feeling that the recipe was
kinda overkill.
Thanks for your help. I didn't learn much about classes, but appreciated
your iter_primes() a lot!
You're welcome, though I can't actually take credit for iter_primes().
The original version is due to Tim Hochberg, in a comment on this recipe:

http://aspn.activestate.com/ASPN/Coo.../Recipe/117119

FWIW, he says that he "managed to generate all primes up to 909,691
before it bombed the Python interpreter mysteriously, but it takes a while!"

I'm not particularly married to that prime generator. For your purposes,
any generator version of iter_primes() is probably more useful than the
class you were looking at. You can see some other implementations of
prime generators on that same recipe page.

STeVe
Aug 13 '07 #9
Steven Bethard wrote:
Dustan wrote:
>On Aug 12, 7:35 pm, Dustan <DustanGro...@g mail.comwrote:
>>On Aug 12, 5:09 pm, Steven Bethard <steven.beth... @gmail.comwrote :

def iter_primes():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count (2)
# generate primes forever
while True:
# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime
# remove all numbers from the (infinite) iterator that are
# divisible by the prime we just generated
numbers = itertools.ifilt er(prime.__rmod __, numbers)
This is kind of OT (from the thread), but in this iter_primes
function, numbers is becoming an ifilter of an ifilter of an ifilter
of an ifilter of an ifilter of an ifilter of... Is that really at all
efficient for larger numbers (millions or billions, or even bigger)?

To word my question better:

How does this algorithm compare and contrast to maintaining a
dictionary or set and iterating through those structures to find out
if a number is divisible? All of those algorithms I've described are
O(n^2), if I'm not mistaken, but as far as memory-efficiency and the
likes, how do they compare/contrast?

I don't have the answer off hand, but if anyone wants to report some
timeit results or memory consumption here, I'd be interested.
Ok, I played around with it myself. Here are the two implementations I
tested::

def iter_primes_rec ursive():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count (2)

# generate primes forever
while True:

# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime

# remove all numbers from the (infinite) iterator that are
# divisible by the prime we just generated
numbers = itertools.ifilt er(prime.__rmod __, numbers)
def iter_primes_map ping():

# mapping from composite number to first prime that revealed
# that number as a composite
composite_to_fa ctor_map = {}

# generate primes forever
for i in itertools.count (2):

# find a factor of the number
factor = composite_to_fa ctor_map.pop(i, None)

# if no factor is found, the number is prime
if factor is None:
yield i
composite_to_fa ctor_map[i * i] = i

# add the factor to the number until we find a new
# composite number
else:
composite = i + factor
while composite in composite_to_fa ctor_map:
composite += factor
composite_to_fa ctor_map[composite] = factor

And here are some timeit results::

$ python -m timeit -s "from script import iter_primes_rec ursive as
iter_primes" "for i in iter_primes():" " if i >= 100:"
" break"
10000 loops, best of 3: 102 usec per loop

$ python -m timeit -s "from script import iter_primes_map ping as
iter_primes" "for i in iter_primes():" " if i >= 100:"
" break"
10000 loops, best of 3: 75.2 usec per loop

$ python -m timeit -s "from script import iter_primes_rec ursive as
iter_primes" "for i in iter_primes():" " if i >= 10000:"
" break"
10 loops, best of 3: 111 msec per loop

$ python -m timeit -s "from script import iter_primes_map ping as
iter_primes" "for i in iter_primes():" " if i >= 10000:"
" break"
100 loops, best of 3: 8.4 msec per loop

So, somewhat unsurprisingly, the non-recursive version is much faster
for larger primes. (Someone should check that both my implementations
are right -- I only did a couple of spot checks on the output.)

STeVe
Aug 13 '07 #10

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

Similar topics

4
1713
by: Piedro | last post by:
Hi group, as I was browsing the web and checking out w3schools.com I read that the font tag was deprecated and that I should use css styles for formatting like for example <p class="p1"> Text goes here </p>
2
1306
by: TGF | last post by:
How do you copy a String type into a native char buffer? Dumb question, but not sure how to do it :( TGF
6
2492
by: wASP | last post by:
Hello everyone, I'm new to C# and ASP.NET, so pardon my stupidity on this one. I'm having a problem with referencing methods/functions external to a class member function. My code is as follows: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11
1614
by: dhnriverside | last post by:
Hi peeps Ok, so I thought I'd have a go at making a console app in VS2k5... I haven't written any windows apps for years, let alone dos apps (been web programming) and I've hit a dumb error... "An object reference is required for the nonstatic field, method or property " This is occuring in my main function...
2
1114
by: Derek Martin | last post by:
Not like I haven't asked dumb ones before, but I want to take my API that I designed and create a DLL out of it, instead of it sitting inside my main form. In VS2K3, how do I go about doing that??? Is that a seperate project and if so, what kind, Class Library Project, or something else? Thanks, Derek
16
1654
by: CMM | last post by:
Is it me or has anyone noticed that F1 is really dumb in VS2005. Since VB3 I have been able to click F1 on an ambiguous method in code and the IDE automatically determines the type based on the code itself and shows the right help topic. This even worked more or less in VS2003. But in VS2005, if I highlight the "Host" method below and hit F1 I get a help topic on the "UriBuilder.Host" property. Huh????? That's dumb. Dim o as New...
10
2269
by: sp | last post by:
I create an xml file in a text editor: <?xml version="1.0" encoding="utf-8"?> <elts> <elt id="1" class="c1">content1</elt> <elt id="2" class="c1">content2</elt> </elts> Then I load the file via xmlHttpRequest into xmlData variable. Why does xmlData.getElementById('1') return null and xmlData.firstChild.childNodes.className returns null also?
7
1123
by: Joel Hedlund | last post by:
Hi! There's one thing about dictionaries and __hash__() methods that puzzle me. I have a class with several data members, one of which is 'name' (a str). I would like to store several of these objects in a dict for quick access ({name:object} style). Now, I was thinking that given a list of objects I might do something like d = {} for o in objects:
3
1605
by: rdufour | last post by:
Downloaded a sample that is supposed to show how to localize a web site and started playing with the code, its in Vs2003, so I figure I would take code and put it in Vs 2005 and doing so use it a bit as a walkthrough on how things are done in VS2005 for this type of stuff. BUT just as I looked into it deeper I noticed the sample is a vb solution and it has 2 projects, each one is a class project. First project is a dll that makes sense to...
0
9712
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10341
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7634
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5530
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.