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


Groups > comp.lang.python > #77590 > unrolled thread

My backwards logic

Started bySeymore4Head <Seymore4Head@Hotmail.invalid>
First post2014-09-05 12:48 -0400
Last post2014-09-06 08:46 +0100
Articles 20 on this page of 39 — 20 participants

Back to article view | Back to comp.lang.python


Contents

  My backwards logic Seymore4Head <Seymore4Head@Hotmail.invalid> - 2014-09-05 12:48 -0400
    Re: My backwards logic MRAB <python@mrabarnett.plus.com> - 2014-09-05 17:57 +0100
    Re: My backwards logic Bob Gailer <bgailer@gmail.com> - 2014-09-05 13:04 -0400
    Re: My backwards logic John Gordon <gordon@panix.com> - 2014-09-05 17:08 +0000
    Re: My backwards logic Ethan Furman <ethan@stoneleaf.us> - 2014-09-05 10:08 -0700
      Re: My backwards logic Seymore4Head <Seymore4Head@Hotmail.invalid> - 2014-09-05 13:44 -0400
        Re: My backwards logic Chris Kaynor <ckaynor@zindagigames.com> - 2014-09-05 11:17 -0700
        Re: My backwards logic Ian Kelly <ian.g.kelly@gmail.com> - 2014-09-05 15:04 -0600
        Re: My backwards logic Chris Angelico <rosuav@gmail.com> - 2014-09-06 09:44 +1000
    Re: My backwards logic Chris Kaynor <ckaynor@zindagigames.com> - 2014-09-05 10:09 -0700
    Re:My backwards logic Dave Angel <davea@davea.name> - 2014-09-05 13:15 -0400
    Re: My backwards logic Ian Kelly <ian.g.kelly@gmail.com> - 2014-09-05 11:17 -0600
    Re: My backwards logic Juan Christian <juan0christian@gmail.com> - 2014-09-05 14:35 -0300
    Re: My backwards logic Ethan Furman <ethan@stoneleaf.us> - 2014-09-05 11:41 -0700
    Re: My backwards logic MRAB <python@mrabarnett.plus.com> - 2014-09-05 19:48 +0100
    Re: My backwards logic Juan Christian <juan0christian@gmail.com> - 2014-09-05 16:34 -0300
      Re: My backwards logic Paul Rubin <no.email@nospam.invalid> - 2014-09-05 13:07 -0700
        Re: My backwards logic Rustom Mody <rustompmody@gmail.com> - 2014-09-05 18:24 -0700
    Re: My backwards logic Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-09-05 20:54 +0100
    Re: My backwards logic Seymore4Head <Seymore4Head@Hotmail.invalid> - 2014-09-05 17:49 -0400
      Re: My backwards logic Chris Kaynor <ckaynor@zindagigames.com> - 2014-09-05 15:14 -0700
        Re: My backwards logic Seymore4Head <Seymore4Head@Hotmail.invalid> - 2014-09-05 18:36 -0400
      Re: My backwards logic Ian Kelly <ian.g.kelly@gmail.com> - 2014-09-05 16:35 -0600
        Re: My backwards logic Seymore4Head <Seymore4Head@Hotmail.invalid> - 2014-09-05 19:05 -0400
      Re: My backwards logic Dave Angel <davea@davea.name> - 2014-09-05 23:10 -0400
    Re: My backwards logic Juan Christian <juan0christian@gmail.com> - 2014-09-05 22:54 -0300
      Re: My backwards logic Rustom Mody <rustompmody@gmail.com> - 2014-09-05 18:58 -0700
    Posting style: interleaved responses (was: My backwards logic) Ben Finney <ben+python@benfinney.id.au> - 2014-09-06 12:37 +1000
    Re: Posting style: interleaved responses (was: My backwards logic) Juan Christian <juan0christian@gmail.com> - 2014-09-06 00:06 -0300
    Re: Posting style: interleaved responses (was: My backwards logic) Zachary Ware <zachary.ware+pylist@gmail.com> - 2014-09-05 23:04 -0500
    Re: My backwards logic Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-09-06 08:45 +0100
    Re: My backwards logic Denis McMahon <denismfmcmahon@gmail.com> - 2014-09-06 07:49 +0000
      Prime testing [was Re: My backwards logic] Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-09-06 20:38 +1000
        Re: Prime testing [was Re: My backwards logic] Chris Angelico <rosuav@gmail.com> - 2014-09-06 20:42 +1000
        Re: Prime testing [was Re: My backwards logic] Manolo Martínez <manolo@austrohungaro.com> - 2014-09-06 12:53 +0200
          Re: Prime testing [was Re: My backwards logic] Peter Pearson <pkpearson@nowhere.invalid> - 2014-09-07 18:53 +0000
            Re: Prime testing [was Re: My backwards logic] Manolo Martínez <manolo@austrohungaro.com> - 2014-09-07 21:09 +0200
            Re: Prime testing [was Re: My backwards logic] Dan Stromberg <drsalists@gmail.com> - 2014-09-07 20:23 -0700
    Re: Posting style: interleaved responses Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-09-06 08:46 +0100

Page 1 of 2  [1] 2  Next page →


#77590 — My backwards logic

FromSeymore4Head <Seymore4Head@Hotmail.invalid>
Date2014-09-05 12:48 -0400
SubjectMy backwards logic
Message-ID<1enj0att6bkrnvb81rhma5dbuk3h28agl8@4ax.com>
I'm still doing practice problems.  I haven't heard from the library
on any of the books I have requested.

http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html

This is not a hard problem, but it got me to thinking a little.  A
prime number will divide by one and itself.  When setting up this
loop, if I start at 2 instead of 1, that automatically excludes one of
the factors.  Then, by default, Python goes "to" the chosen count and
not "through" the count, so just the syntax causes Python to rule out
the other factor (the number itself).

So this works:
while True:
    a=random.randrange(1,8)
    print (a)
    for x in range(2,a):
        if a%x==0:
            print ("Number is not prime")
            break
    wait = input (" "*40  + "Wait")

But, what this instructions want printed is "This is a prime number"
So how to I use this code logic NOT print (not prime) and have the
logic print "This number is prime"

[toc] | [next] | [standalone]


#77591

FromMRAB <python@mrabarnett.plus.com>
Date2014-09-05 17:57 +0100
Message-ID<mailman.13792.1409936285.18130.python-list@python.org>
In reply to#77590
On 2014-09-05 17:48, Seymore4Head wrote:
> I'm still doing practice problems.  I haven't heard from the library
> on any of the books I have requested.
>
> http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
>
> This is not a hard problem, but it got me to thinking a little.  A
> prime number will divide by one and itself.  When setting up this
> loop, if I start at 2 instead of 1, that automatically excludes one of
> the factors.  Then, by default, Python goes "to" the chosen count and
> not "through" the count, so just the syntax causes Python to rule out
> the other factor (the number itself).
>
> So this works:
> while True:
>      a=random.randrange(1,8)
>      print (a)
>      for x in range(2,a):
>          if a%x==0:
>              print ("Number is not prime")
>              break
>      wait = input (" "*40  + "Wait")
>
> But, what this instructions want printed is "This is a prime number"
> So how to I use this code logic NOT print (not prime) and have the
> logic print "This number is prime"
>
Look for a factor. If you don't find one, it's a prime number.

[toc] | [prev] | [next] | [standalone]


#77593

FromBob Gailer <bgailer@gmail.com>
Date2014-09-05 13:04 -0400
Message-ID<mailman.13794.1409936673.18130.python-list@python.org>
In reply to#77590

[Multipart message — attachments visible in raw view] — view raw

Bob gailer
On Sep 5, 2014 12:51 PM, "Seymore4Head" <Seymore4Head@hotmail.invalid>
wrote:
>
> I'm still doing practice problems.  I haven't heard from the library
> on any of the books I have requested.
>
>
http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
>
> This is not a hard problem, but it got me to thinking a little.  A
> prime number will divide by one and itself.  When setting up this
> loop, if I start at 2 instead of 1, that automatically excludes one of
> the factors.  Then, by default, Python goes "to" the chosen count and
> not "through" the count, so just the syntax causes Python to rule out
> the other factor (the number itself).
>
> So this works:
> while True:
>     a=random.randrange(1,8)
>     print (a)
>     for x in range(2,a):
>         if a%x==0:
>             print ("Number is not prime")
>             break
       else:
           print ...
>     wait = input (" "*40  + "Wait")
>
> But, what this instructions want printed is "This is a prime number"
> So how to I use this code logic NOT print (not prime) and have the
> logic print "This number is prime"
>
> --
> https://mail.python.org/mailman/listinfo/python-list

[toc] | [prev] | [next] | [standalone]


#77594

FromJohn Gordon <gordon@panix.com>
Date2014-09-05 17:08 +0000
Message-ID<lucqll$s6c$1@reader1.panix.com>
In reply to#77590
In <1enj0att6bkrnvb81rhma5dbuk3h28agl8@4ax.com> Seymore4Head <Seymore4Head@Hotmail.invalid> writes:

> I'm still doing practice problems.  I haven't heard from the library
> on any of the books I have requested.

> http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html

> This is not a hard problem, but it got me to thinking a little.  A
> prime number will divide by one and itself.  When setting up this
> loop, if I start at 2 instead of 1, that automatically excludes one of
> the factors.  Then, by default, Python goes "to" the chosen count and
> not "through" the count, so just the syntax causes Python to rule out
> the other factor (the number itself).

> So this works:
> while True:
>     a=random.randrange(1,8)
>     print (a)
>     for x in range(2,a):
>         if a%x==0:
>             print ("Number is not prime")
>             break
>     wait = input (" "*40  + "Wait")

> But, what this instructions want printed is "This is a prime number"
> So how to I use this code logic NOT print (not prime) and have the
> logic print "This number is prime"


There are two basic tactics you can use:

1. Initialize an "isprime" flag to True at the top of the while loop.  
   In the for loop, replace the print statement with a statement that
   sets isprime to False.  After the for loop, insert a check on isprime,
   and print "This number is prime" if isprime is still True.

2. Create a separate function just for testing if a number is prime, which
   returns True or False.  Then call that function within your while loop.

-- 
John Gordon         Imagine what it must be like for a real medical doctor to
gordon@panix.com    watch 'House', or a real serial killer to watch 'Dexter'.

[toc] | [prev] | [next] | [standalone]


#77595

FromEthan Furman <ethan@stoneleaf.us>
Date2014-09-05 10:08 -0700
Message-ID<mailman.13795.1409936907.18130.python-list@python.org>
In reply to#77590
On 09/05/2014 09:48 AM, Seymore4Head wrote:
> I'm still doing practice problems.  I haven't heard from the library
> on any of the books I have requested.
>
> http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
>
> This is not a hard problem, but it got me to thinking a little.  A
> prime number will divide by one and itself.  When setting up this
> loop, if I start at 2 instead of 1, that automatically excludes one of
> the factors.  Then, by default, Python goes "to" the chosen count and
> not "through" the count, so just the syntax causes Python to rule out
> the other factor (the number itself).
>
> So this works:
> while True:
>      a=random.randrange(1,8)
>      print (a)
>      for x in range(2,a):
>          if a%x==0:
>              print ("Number is not prime")
>              break
>      wait = input (" "*40  + "Wait")
>
> But, what this instructions want printed is "This is a prime number"
> So how to I use this code logic NOT print (not prime) and have the
> logic print "This number is prime"

Python's 'for' loop has a handy 'else' extension which is perfect for the search-type of 'for' loop:

    while True:
         a=random.randrange(1,8)
         print (a)
         for x in range(2,a):
             if a%x==0:
                 print ("Number is not prime")
                 break
         else:
             print ("Number is prime")
         wait = input (" "*40  + "Wait")

Note the two lines I added after the 'break' and before the 'wait'.

--
~Ethan~

[toc] | [prev] | [next] | [standalone]


#77602

FromSeymore4Head <Seymore4Head@Hotmail.invalid>
Date2014-09-05 13:44 -0400
Message-ID<a1tj0a9sb7bo0qd2lpf7gl9gu3l0o1sniu@4ax.com>
In reply to#77595
On Fri, 05 Sep 2014 10:08:18 -0700, Ethan Furman <ethan@stoneleaf.us>
wrote:

>On 09/05/2014 09:48 AM, Seymore4Head wrote:
>> I'm still doing practice problems.  I haven't heard from the library
>> on any of the books I have requested.
>>
>> http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
>>
>> This is not a hard problem, but it got me to thinking a little.  A
>> prime number will divide by one and itself.  When setting up this
>> loop, if I start at 2 instead of 1, that automatically excludes one of
>> the factors.  Then, by default, Python goes "to" the chosen count and
>> not "through" the count, so just the syntax causes Python to rule out
>> the other factor (the number itself).
>>
>> So this works:
>> while True:
>>      a=random.randrange(1,8)
>>      print (a)
>>      for x in range(2,a):
>>          if a%x==0:
>>              print ("Number is not prime")
>>              break
>>      wait = input (" "*40  + "Wait")
>>
>> But, what this instructions want printed is "This is a prime number"
>> So how to I use this code logic NOT print (not prime) and have the
>> logic print "This number is prime"
>
>Python's 'for' loop has a handy 'else' extension which is perfect for the search-type of 'for' loop:
>
>    while True:
>         a=random.randrange(1,8)
>         print (a)
>         for x in range(2,a):
>             if a%x==0:
>                 print ("Number is not prime")
>                 break
>         else:
>             print ("Number is prime")
>         wait = input (" "*40  + "Wait")
>
>Note the two lines I added after the 'break' and before the 'wait'.

I had already tried this one.
The solution I want should only print:
"This number is prime"

Adding else causes the program to also print "This number is not
prime"

I also tried the flag=True suggestion, but never got one that worked.
I am unsure when to use flag=True and flag==True 
Then there is flag="True" and flag=="True"

What I really wanted was something like:
if !(a%x==0)

BTW since I am getting no grade, I much prefer the answer than a hint.
The best hint IMO is to tell me how you would do it.

Thanks everyone

[toc] | [prev] | [next] | [standalone]


#77605

FromChris Kaynor <ckaynor@zindagigames.com>
Date2014-09-05 11:17 -0700
Message-ID<mailman.13802.1409941356.18130.python-list@python.org>
In reply to#77602

[Multipart message — attachments visible in raw view] — view raw

On Fri, Sep 5, 2014 at 10:44 AM, Seymore4Head <Seymore4Head@hotmail.invalid>
wrote:

> On Fri, 05 Sep 2014 10:08:18 -0700, Ethan Furman <ethan@stoneleaf.us>
> wrote:
>
> >On 09/05/2014 09:48 AM, Seymore4Head wrote:
> >> I'm still doing practice problems.  I haven't heard from the library
> >> on any of the books I have requested.
> >>
> >>
> http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
> >>
> >> This is not a hard problem, but it got me to thinking a little.  A
> >> prime number will divide by one and itself.  When setting up this
> >> loop, if I start at 2 instead of 1, that automatically excludes one of
> >> the factors.  Then, by default, Python goes "to" the chosen count and
> >> not "through" the count, so just the syntax causes Python to rule out
> >> the other factor (the number itself).
> >>
> >> So this works:
> >> while True:
> >>      a=random.randrange(1,8)
> >>      print (a)
> >>      for x in range(2,a):
> >>          if a%x==0:
> >>              print ("Number is not prime")
> >>              break
> >>      wait = input (" "*40  + "Wait")
> >>
> >> But, what this instructions want printed is "This is a prime number"
> >> So how to I use this code logic NOT print (not prime) and have the
> >> logic print "This number is prime"
> >
> >Python's 'for' loop has a handy 'else' extension which is perfect for the
> search-type of 'for' loop:
> >
> >    while True:
> >         a=random.randrange(1,8)
> >         print (a)
> >         for x in range(2,a):
> >             if a%x==0:
> >                 print ("Number is not prime")
> >                 break
> >         else:
> >             print ("Number is prime")
> >         wait = input (" "*40  + "Wait")
> >
> >Note the two lines I added after the 'break' and before the 'wait'.
>
> I had already tried this one.
> The solution I want should only print:
> "This number is prime"
>
> Adding else causes the program to also print "This number is not
> prime"
>

If you do not want it to print the "Number is not prime", just remove the
print("Number is not prime") line.


> I also tried the flag=True suggestion, but never got one that worked.
> I am unsure when to use flag=True and flag==True
> Then there is flag="True" and flag=="True"
>

Generally, you would want to use:

flag = False

 before the loop, and

flag = True

inside the loop (once you know the number is not prime). After the loop,
you would typically just use:

if flag: # This could be "if flag == True:", however the plain "if flag:"
is more Pythonic.

print("Number is prime")


The "=" operator is assignment - storing a new value.
The "==" operator is for equality checking. The inverse is the "!="
operator which checks for inequality.

What I really wanted was something like:
> if !(a%x==0)


In this case, that will not work, as you only know that the number is prime
after checking all the values, which means after the loop has completed.

Ignoring the fact that it would not function for this use case, the proper
Python syntax for that would be one of:

   - if a%x != 0: # Probably the clearest for this case.
   - if not (a%x==0):

[toc] | [prev] | [next] | [standalone]


#77618

FromIan Kelly <ian.g.kelly@gmail.com>
Date2014-09-05 15:04 -0600
Message-ID<mailman.13811.1409951086.18130.python-list@python.org>
In reply to#77602
On Fri, Sep 5, 2014 at 11:44 AM, Seymore4Head
<Seymore4Head@hotmail.invalid> wrote:
> BTW since I am getting no grade, I much prefer the answer than a hint.
> The best hint IMO is to tell me how you would do it.

from math import ceil, sqrt

def is_prime(n):
    if n < 2:
        return False
    if n % 2 == 0:
        return n == 2
    return all(n % x != 0 for x in range(3, int(sqrt(n)) + 1, 2))

while True:
    n = int(input("Enter a number: "))
    if is_prime(n):
        print("{} is prime.".format(n))
    else:
        print("{} is not prime.".format(n))

[toc] | [prev] | [next] | [standalone]


#77626

FromChris Angelico <rosuav@gmail.com>
Date2014-09-06 09:44 +1000
Message-ID<mailman.13814.1409960691.18130.python-list@python.org>
In reply to#77602
On Sat, Sep 6, 2014 at 3:44 AM, Seymore4Head
<Seymore4Head@hotmail.invalid> wrote:
> BTW since I am getting no grade, I much prefer the answer than a hint.
> The best hint IMO is to tell me how you would do it.

But for your own learning, it's still better for you to do things
yourself. Giving you the answer doesn't teach you nearly as
effectively as giving you a hint and having you work out the answer
yourself.

But telling you how we'd do it can be useful too, especially when we
get down to the detaily bits where there are lots of ways to do
things. For instance, there's been a suggestion made a few times to
break the primality test out into a function... but compare these two:

def isprime(n):
   """Return True iff n is prime"""

def find_factor(n):
    """Return a factor of n, or None if n is prime"""

Aside from inverting the truth value, these are both tests of
primality - you can write "if isprime(n):" or "if find_factor(n):" and
they'll both work. (The latter is actually "iscomposite".) But the
second function is giving you a bit more information - it tells you
what factor it found.

As a general rule, try to avoid throwing information away. To prove
that n is composite, your function found a factor. Returning that,
rather than a boolean value, might make your function more useful; and
it's zero cost, because you know that factors of a number will never
be zero.

ChrisA

[toc] | [prev] | [next] | [standalone]


#77596

FromChris Kaynor <ckaynor@zindagigames.com>
Date2014-09-05 10:09 -0700
Message-ID<mailman.13796.1409936972.18130.python-list@python.org>
In reply to#77590

[Multipart message — attachments visible in raw view] — view raw

On Fri, Sep 5, 2014 at 9:48 AM, Seymore4Head <Seymore4Head@hotmail.invalid>
wrote:

> I'm still doing practice problems.  I haven't heard from the library
> on any of the books I have requested.
>
>
> http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
>
> This is not a hard problem, but it got me to thinking a little.  A
> prime number will divide by one and itself.  When setting up this
> loop, if I start at 2 instead of 1, that automatically excludes one of
> the factors.  Then, by default, Python goes "to" the chosen count and
> not "through" the count, so just the syntax causes Python to rule out
> the other factor (the number itself).
>
> So this works:
> while True:
>     a=random.randrange(1,8)
>     print (a)
>     for x in range(2,a):
>         if a%x==0:
>             print ("Number is not prime")
>             break
>     wait = input (" "*40  + "Wait")
>
> But, what this instructions want printed is "This is a prime number"
> So how to I use this code logic NOT print (not prime) and have the
> logic print "This number is prime"
>
>
One neat feature of Python is the for...else function. The code inside the
else block will run only if the loop ran to completion (untested code
follows):

while True:
    a=random.randrange(1,8)
    print (a)
    for x in range(2,a):
        if a%x==0:
            print ("Number is not prime")
            break
    else:
        print("Number is prime")
    wait = input (" "*40  + "Wait")


Depending on how advanced you want to get (I know you are relatively new to
Python), another decent way would be to extract the prime check to a
function, and return the result, and print based on that result (again,
untested code):

def isPrime(number):
    for x in range(2,a):
        if a%x==0:
            return False
    return True

while True:
    a=random.randrange(1,8)
    print (a)
    if isPrime(a):
        print("Number is prime")
    else:
        print("Number is not prime")
    wait = input (" "*40  + "Wait")

[toc] | [prev] | [next] | [standalone]


#77597

FromDave Angel <davea@davea.name>
Date2014-09-05 13:15 -0400
Message-ID<mailman.13797.1409937228.18130.python-list@python.org>
In reply to#77590
Seymore4Head <Seymore4Head@Hotmail.invalid> Wrote in message:
> I'm still doing practice problems.  I haven't heard from the library
> on any of the books I have requested.
> 
> http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
> 
> This is not a hard problem, but it got me to thinking a little.  A
> prime number will divide by one and itself.  When setting up this
> loop, if I start at 2 instead of 1, that automatically excludes one of
> the factors.  Then, by default, Python goes "to" the chosen count and
> not "through" the count, so just the syntax causes Python to rule out
> the other factor (the number itself).
> 
> So this works:
> while True:
>     a=random.randrange(1,8)
>     print (a)
>     for x in range(2,a):
>         if a%x==0:
>             print ("Number is not prime")
>             break
>     wait = input (" "*40  + "Wait")
> 
> But, what this instructions want printed is "This is a prime number"
> So how to I use this code logic NOT print (not prime) and have the
> logic print "This number is prime"
> 
> 

The traditional way of telling whether something happened in a
 loop is to set a flag to False outside the loop,  and
 conditionally set it to True in the if test. Then after the loop,
 check your flag.

Python however has a better way. You can put an else clause on the
 for loop:


 for x in range(2,a):
        if a%x==0:
           print ("Number is not prime")
           break
  else:
        print ("Number is prime")

The else clause fires if no break executed. 

There are also ways to do it using not, any, and a list
 comprehension, no explicit loop at all.

-- 
DaveA

[toc] | [prev] | [next] | [standalone]


#77599

FromIan Kelly <ian.g.kelly@gmail.com>
Date2014-09-05 11:17 -0600
Message-ID<mailman.13798.1409937511.18130.python-list@python.org>
In reply to#77590
On Fri, Sep 5, 2014 at 11:08 AM, Ethan Furman <ethan@stoneleaf.us> wrote:
> Python's 'for' loop has a handy 'else' extension which is perfect for the
> search-type of 'for' loop:
>
>    while True:
>         a=random.randrange(1,8)
>         print (a)
>         for x in range(2,a):
>             if a%x==0:
>                 print ("Number is not prime")
>                 break
>         else:
>             print ("Number is prime")
>         wait = input (" "*40  + "Wait")
>
> Note the two lines I added after the 'break' and before the 'wait'.

Also note that this construct tends to be particularly sensitive to
indentation. If you accidentally indent the else block one level too
many (which your editor may well do for you to "helpfully" match it up
with the if), then you'll get a completely different result.

I would not worry about the else clause as a beginner, as it's
relatively unique to Python and tends to be somewhat confusing. Use a
flag or refactor the function instead.

[toc] | [prev] | [next] | [standalone]


#77601

FromJuan Christian <juan0christian@gmail.com>
Date2014-09-05 14:35 -0300
Message-ID<mailman.13800.1409938576.18130.python-list@python.org>
In reply to#77590

[Multipart message — attachments visible in raw view] — view raw

I made this code just for fun and learning, it's working, but would this be
a good approach? Thanks.

import sys


def prime_checker(start = 1, stop = 1):
for number in range(start, stop + 1):
divisors = [(number % x) for x in range(1, number + 1)]
print("{n} prime? {r}".format(n = number, r = (divisors.count(0) == 2)))


if __name__ == '__main__':
prime_checker(int(sys.argv[1]), int(sys.argv[2]))


On Fri, Sep 5, 2014 at 2:17 PM, Ian Kelly <ian.g.kelly@gmail.com> wrote:

> On Fri, Sep 5, 2014 at 11:08 AM, Ethan Furman <ethan@stoneleaf.us> wrote:
> > Python's 'for' loop has a handy 'else' extension which is perfect for the
> > search-type of 'for' loop:
> >
> >    while True:
> >         a=random.randrange(1,8)
> >         print (a)
> >         for x in range(2,a):
> >             if a%x==0:
> >                 print ("Number is not prime")
> >                 break
> >         else:
> >             print ("Number is prime")
> >         wait = input (" "*40  + "Wait")
> >
> > Note the two lines I added after the 'break' and before the 'wait'.
>
> Also note that this construct tends to be particularly sensitive to
> indentation. If you accidentally indent the else block one level too
> many (which your editor may well do for you to "helpfully" match it up
> with the if), then you'll get a completely different result.
>
> I would not worry about the else clause as a beginner, as it's
> relatively unique to Python and tends to be somewhat confusing. Use a
> flag or refactor the function instead.
> --
> https://mail.python.org/mailman/listinfo/python-list
>

[toc] | [prev] | [next] | [standalone]


#77607

FromEthan Furman <ethan@stoneleaf.us>
Date2014-09-05 11:41 -0700
Message-ID<mailman.13804.1409942486.18130.python-list@python.org>
In reply to#77590
On 09/05/2014 10:17 AM, Ian Kelly wrote:
>
> I would not worry about the else clause as a beginner, as it's
> relatively unique to Python and tends to be somewhat confusing. Use a
> flag or refactor the function instead.

I don't disagree with this, but early exposure to "for..else is for search loops" is a good thing.  I still get tripped 
up by this as I didn't learn it that way.

--
~Ethan~

[toc] | [prev] | [next] | [standalone]


#77608

FromMRAB <python@mrabarnett.plus.com>
Date2014-09-05 19:48 +0100
Message-ID<mailman.13805.1409942918.18130.python-list@python.org>
In reply to#77590
On 2014-09-05 18:35, Juan Christian wrote:
> I made this code just for fun and learning, it's working, but would this
> be a good approach? Thanks.
>
> import sys
>
>
> def prime_checker(start = 1, stop = 1):

In Python, the standard is to use a half-open range.

>     for number in range(start, stop + 1):
>         divisors = [(number % x) for x in range(1, number + 1)]
>             print("{n} prime? {r}".format(n = number, r = (divisors.count(0) == 2)))
>
You want to know only whether it's prime, so why continue looking after
finding a factor?
>
> if __name__ == '__main__':
>     prime_checker(int(sys.argv[1]), int(sys.argv[2]))
>
[snip]

[toc] | [prev] | [next] | [standalone]


#77612

FromJuan Christian <juan0christian@gmail.com>
Date2014-09-05 16:34 -0300
Message-ID<mailman.13807.1409946021.18130.python-list@python.org>
In reply to#77590

[Multipart message — attachments visible in raw view] — view raw

What's [snip] ??


On Fri, Sep 5, 2014 at 3:48 PM, MRAB <python@mrabarnett.plus.com> wrote:

> On 2014-09-05 18:35, Juan Christian wrote:
>
>> I made this code just for fun and learning, it's working, but would this
>> be a good approach? Thanks.
>>
>> import sys
>>
>>
>> def prime_checker(start = 1, stop = 1):
>>
>
> In Python, the standard is to use a half-open range.
>
>      for number in range(start, stop + 1):
>>         divisors = [(number % x) for x in range(1, number + 1)]
>>             print("{n} prime? {r}".format(n = number, r =
>> (divisors.count(0) == 2)))
>>
>>  You want to know only whether it's prime, so why continue looking after
> finding a factor?
>
>>
>> if __name__ == '__main__':
>>     prime_checker(int(sys.argv[1]), int(sys.argv[2]))
>>
>>  [snip]
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>

[toc] | [prev] | [next] | [standalone]


#77614

FromPaul Rubin <no.email@nospam.invalid>
Date2014-09-05 13:07 -0700
Message-ID<7x38c5u8z6.fsf@ruckus.brouhaha.com>
In reply to#77612
Juan Christian <juan0christian@gmail.com> writes:
>  I made this code just for fun and learning, it's working, but would
>  this be a good approach? Thanks. ...
>  ** ** for number in range(start, stop + 1):
>  ** ** ** ** divisors = [(number % x) for x in range(1, number + 1)]
>  ** ** ** ** ** ** print("{n} prime? {r}".format(n = number, r =
>  (divisors.count(0) == 2)))

1. Mathematically it's better to stop checking once you've gone past
the square root of the number, since if n = p*q and is composite,
then at least one of p,q will be <= sqrt(n).

2. As a program design matter, it's generally preferable for functions
like this to not print the answer.  They should just return a value, in
this case a bool indicating whether the number is prime.  That makes it
easier to re-use the function, to wrap it in a unit test framework, etc.
If you want to print the result, then call the function and have the
caller print the returned value.

3. As a simple optimization, once you have checked that the number is
not divisible by 2, you don't have to check for other even divisors.
So just check for 2, then the odd numbers 3,5,7...

This is a little bit fancy but I like to use itertools for these
sorts of problems:

  from itertools import chain, takewhile, count

  def is_prime(n):
      if n < 2: return False
      candidates = chain([2], count(3,2))
      return all(n%d!=0 for d in takewhile(lambda d: d*d<=n, candidates))

If you're not familiar with those functions, "chain" concatenates
two sequences, and "count(n,i)" gives an increasing sequence starting
with n and incrementing by i.  So chain([2], count(3,2)) gives
the unending sequence [2, 3, 5, 7, 9, ...] which is the numbers
you want to check against.  Then the takewhile expression chops
that sequence once it gets past sqrt(n), and "all" returns true iff
all of the candidate divisors fail to divide the number.

[toc] | [prev] | [next] | [standalone]


#77628

FromRustom Mody <rustompmody@gmail.com>
Date2014-09-05 18:24 -0700
Message-ID<06b5d0e1-4e8c-44f7-bcd2-976b14004695@googlegroups.com>
In reply to#77614
On Saturday, September 6, 2014 1:37:57 AM UTC+5:30, Paul Rubin wrote:
> Juan Christian  writes:
> >  I made this code just for fun and learning, it's working, but would
> >  this be a good approach? Thanks. ...
> >  ** ** for number in range(start, stop + 1):
> >  ** ** ** ** divisors = [(number % x) for x in range(1, number + 1)]
> >  ** ** ** ** ** ** print("{n} prime? {r}".format(n = number, r =
> >  (divisors.count(0) == 2)))

> 1. Mathematically it's better to stop checking once you've gone past
> the square root of the number, since if n = p*q and is composite,
> then at least one of p,q will be <= sqrt(n).

> 2. As a program design matter, it's generally preferable for functions
> like this to not print the answer.  They should just return a value, in
> this case a bool indicating whether the number is prime.  That makes it
> easier to re-use the function, to wrap it in a unit test framework, etc.
> If you want to print the result, then call the function and have the
> caller print the returned value.

Hoo boy! And we come full circle

> 3. As a simple optimization, once you have checked that the number is
> not divisible by 2, you don't have to check for other even divisors.
> So just check for 2, then the odd numbers 3,5,7...

> This is a little bit fancy but I like to use itertools for these
> sorts of problems:

>   from itertools import chain, takewhile, count

>   def is_prime(n):
>       if n < 2: return False
>       candidates = chain([2], count(3,2))
>       return all(n%d!=0 for d in takewhile(lambda d: d*d<=n, candidates))

Paul's suggestions without the fancy -- no sqrt stop, no generators, no itertools
etc -- (all to be learnt at their time of course!)


First of all I make for myself a closed range

>>> def crange(a,b) : return range(a,b+1)

Check it

>>> crange(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Now for divisors of a number

>>> def divisors(n): return [fact for fact in crange(1,n) if n%fact == 0]

Check it

>>> divisors(4)
[1,2,4]

>>> divisors(7)
[1, 7]

So now a prime is a number n whose divisors are only 1 and n

>>> def is_prime(n): return divisors(n) == [1,n]

>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(5)
True
>>> is_prime(6)
False
>>> is_prime(7)
True

So collecting the code together

>>> def crange(a,b): return range(a,b+1)
>>> def divisors(n): return [fact for fact in crange(1,n) if n%fact == 0]
>>> def is_prime(n): return divisors(n) == [1,n]

[toc] | [prev] | [next] | [standalone]


#77613

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2014-09-05 20:54 +0100
Message-ID<mailman.13808.1409946891.18130.python-list@python.org>
In reply to#77590
On 05/09/2014 20:34, Juan Christian wrote:
> What's [snip] ??
>

As in cut out or chopped out such that some of the original text has 
been removed.  And please don't top post here, thanks.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

[toc] | [prev] | [next] | [standalone]


#77619

FromSeymore4Head <Seymore4Head@Hotmail.invalid>
Date2014-09-05 17:49 -0400
Message-ID<6ebk0a95ia9llot967jf7hpmidhh6hl4fd@4ax.com>
In reply to#77590
On Fri, 05 Sep 2014 12:48:56 -0400, Seymore4Head
<Seymore4Head@Hotmail.invalid> wrote:

>I'm still doing practice problems.  I haven't heard from the library
>on any of the books I have requested.
>
>http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
>
>This is not a hard problem, but it got me to thinking a little.  A
>prime number will divide by one and itself.  When setting up this
>loop, if I start at 2 instead of 1, that automatically excludes one of
>the factors.  Then, by default, Python goes "to" the chosen count and
>not "through" the count, so just the syntax causes Python to rule out
>the other factor (the number itself).
>
>So this works:
>while True:
>    a=random.randrange(1,8)
>    print (a)
>    for x in range(2,a):
>        if a%x==0:
>            print ("Number is not prime")
>            break
>    wait = input (" "*40  + "Wait")
>
>But, what this instructions want printed is "This is a prime number"
>So how to I use this code logic NOT print (not prime) and have the
>logic print "This number is prime"

I am sure this has already been done, but after it was pointed out
that you don't need to test for any number that multiplies by 2 it
made me think again.

If you start with the list [3,5,7] and step through the list of all
remaining odd numbers (step 2), and start appending numbers that won't
divide by numbers already appended in the list, that would seem like a
pretty efficient way to find all prime numbers.

[toc] | [prev] | [next] | [standalone]


Page 1 of 2  [1] 2  Next page →

Back to top | Article view | comp.lang.python


csiph-web