Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #20461
| Date | 2012-02-15 13:45 -0500 |
|---|---|
| From | Dave Angel <d@davea.name> |
| Subject | Re: Complexity question on Python 3 lists |
| References | <franck-B0D585.19202115022012@news.free.fr> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.5844.1329331566.27778.python-list@python.org> (permalink) |
On 02/15/2012 01:20 PM, Franck Ditter wrote: > What is the cost of calling primes(n) below ? I'm mainly interested in > knowing if the call to append is O(1), even amortized. > Do lists in Python 3 behave like ArrayList in Java (if the capacity > is full, then the array grows by more than 1 element) ? > > def sdiv(n) : # n>= 2 > """returns the smallest (prime) divisor of n""" > if n % 2 == 0 : return 2 > for d in range(3,int(sqrt(n))+1,2) : > if n % d == 0 : return d > return n > > def isPrime(n) : > """Returns True iff n is prime""" > return n>= 2 and n == sdiv(n) > > def primes(n) : # n>= 2 > """Returns the list of primes in [2,n]""" > res = [] > for k in range(2,n+1) : > if isPrime(k) : res.append(k) # cost O(1) ? > return res > > Thanks, > > franck Yes, lists behave the way you'd expect (see vector in C++), where when they have to reallocate they do so exponentially. However, realize that your algorithm is inefficient by a huge factor more than any time spent expanding lists. The biggest single thing you need to do is to memoize -- store the list of known primes, and add to it as you encounter more. Then use that list instead of range(3, xxx, 2) for doing the trial divisions. -- DaveA
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Complexity question on Python 3 lists Franck Ditter <franck@ditter.org> - 2012-02-15 19:20 +0100 Re: Complexity question on Python 3 lists Chris Rebert <clp2@rebertia.com> - 2012-02-15 10:35 -0800 Re: Complexity question on Python 3 lists Ian Kelly <ian.g.kelly@gmail.com> - 2012-02-15 11:43 -0700 Re: Complexity question on Python 3 lists Dave Angel <d@davea.name> - 2012-02-15 13:45 -0500 Re: Complexity question on Python 3 lists Stefan Behnel <stefan_ml@behnel.de> - 2012-02-15 20:01 +0100 Re: Complexity question on Python 3 lists Chris Rebert <clp2@rebertia.com> - 2012-02-15 11:11 -0800 Re: Complexity question on Python 3 lists Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2012-02-15 15:28 -0500 Re: Complexity question on Python 3 lists Terry Reedy <tjreedy@udel.edu> - 2012-02-15 16:41 -0500 Re: Complexity question on Python 3 lists Ian Kelly <ian.g.kelly@gmail.com> - 2012-02-15 15:54 -0700 Re: Complexity question on Python 3 lists Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-02-16 00:41 +0000
csiph-web