Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #89662

Re: Lucky numbers in Python

Date 2015-04-30 15:28 -0400
From Dave Angel <davea@davea.name>
Subject Re: Lucky numbers in Python
References <87lhhabxod.fsf@Equus.decebal.nl> <87fv7htpip.fsf@Equus.decebal.nl>
Newsgroups comp.lang.python
Message-ID <mailman.142.1430422160.3680.python-list@python.org> (permalink)

Show all headers | View raw


On 04/30/2015 02:55 PM, Cecil Westerhof wrote:
> Because I want the code to work with Python 3 also, the code is now:
>      def lucky_numbers(n):
>          """
>          Lucky numbers from 1 up-to n
>          http://en.wikipedia.org/wiki/Lucky_number
>          """
>
>          if n < 3:
>              return [1]
>          sieve = list(range(1, n + 1, 2))
>          sieve_index = 1
>          while True:
>              sieve_len   = len(sieve)
>              if (sieve_index + 1) > sieve_len:
>                  break
>              skip_count  = sieve[sieve_index]
>              if sieve_len < skip_count:
>                  break
>              del sieve[skip_count - 1 : : skip_count]
>              sieve_index += 1
>          return sieve
>
> It looks like the list in:
>          sieve = list(range(1, n + 1, 2))
>
> does not have much influence in Python 2. So I was thinking of leaving
> the code like it is. Or is it better to check and do the list only
> with Python 3?
>

I'd do something like this at top of the module:

try:
     range = xrange
except NameError as ex:
     pass

then use range as it is defined in Python3.

if that makes you nervous, then define irange = xrange, and if it gets a 
NameError exception, irange = range


-- 
DaveA

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Lucky numbers in Python Cecil Westerhof <Cecil@decebal.nl> - 2015-04-29 20:24 +0200
  Re: Lucky numbers in Python Ian Kelly <ian.g.kelly@gmail.com> - 2015-04-29 13:57 -0600
    Re: Lucky numbers in Python Cecil Westerhof <Cecil@decebal.nl> - 2015-04-29 23:45 +0200
      Re: Lucky numbers in Python Ian Kelly <ian.g.kelly@gmail.com> - 2015-04-29 16:38 -0600
        Re: Lucky numbers in Python Cecil Westerhof <Cecil@decebal.nl> - 2015-04-30 02:01 +0200
          Re: Lucky numbers in Python Ian Kelly <ian.g.kelly@gmail.com> - 2015-04-29 20:55 -0600
            Re: Lucky numbers in Python Cecil Westerhof <Cecil@decebal.nl> - 2015-04-30 08:34 +0200
      Re: Lucky numbers in Python Chris Kaynor <ckaynor@zindagigames.com> - 2015-04-29 15:56 -0700
    Re: Lucky numbers in Python Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-04-30 10:11 +1000
      Re: Lucky numbers in Python Ian Kelly <ian.g.kelly@gmail.com> - 2015-04-29 21:08 -0600
  Re: Lucky numbers in Python Cecil Westerhof <Cecil@decebal.nl> - 2015-04-30 20:55 +0200
    Re: Lucky numbers in Python Dave Angel <davea@davea.name> - 2015-04-30 15:28 -0400

csiph-web