[Tutor] Generate Prime Numbers

Cameron Simpson cs at zip.com.au
Sat May 30 01:37:38 CEST 2015


On 29May2015 18:48, alan.gauld at btinternet.com <alan.gauld at btinternet.com> wrote:
>On 29/05/15 16:28, Mirage Web Studio wrote:
>>def IsDivisibleBy3(number):#string variable
>>     v=0
>>     for c in number:
>>         v=v+int(c)
>>     if v%3==0:
>>         return True
>>     else:
>>         return False
>
>def IsDivisibleBy3(number):#string variable
>    return not int(number) % 3

To illustrate that there isn't just One Right Way, I would code the above like 
this:

  def IsDivisibleBy3(number): #string variable
      return int(number) % 3 == 0

Alan's code relies on "not" using an expressions "nonzero"ness as a boolean 
value. I _much_ prefer to directly state the test instead of relying on magic 
numeric=>boolean effects.

The only other remark I would make is that it is probably a ba idea to write 
this function to take a string. It expresses a numerics test - make it take a 
number! Do the string conversion-to-int outside the function before it is 
called.

>>def IsDivisibleBy7(number):#string variable
>
>See above, but maybe better still
>
>def isDivisibleByN(number, N):
>   return not int(number)%N

Indeed, but again I would write an outright numeric expression and not rely on 
"not(numeric-expression)".

>>def IsPrime(number):
>
>Google for the "sieve of eratosthenes"
>Or look it up on wikipedia.
>That will give one of several possible
>improvements to your algorithm.

Plus, it is incredibly easy to code the SoE in Python. So easy that I once did 
it in about a minute in a Code Wars session. It is a lovely algorithm which is 
easy to remember.

>>primelist=[]
>>
>>for i in range (11,200000,2):
>>     number=str(i)
>>     print "checking ",i
>>
>>     if IsPrime(number):
>
>Note, you are starting with a number, then converting
>it to a string then in your functions converting it
>back to a number.
>That's crazy!

Indeed! Numbers throughout if at all possible.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list