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


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

Short-circuit Logic

Started byAhmed Abdulshafy <abdulshafy@gmail.com>
First post2013-05-26 04:11 -0700
Last post2013-05-27 21:36 -0400
Articles 11 on this page of 71 — 22 participants

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


Contents

  Short-circuit Logic Ahmed Abdulshafy <abdulshafy@gmail.com> - 2013-05-26 04:11 -0700
    Re: Short-circuit Logic Roy Smith <roy@panix.com> - 2013-05-26 07:38 -0400
    Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-26 12:13 +0000
      Re: Short-circuit Logic Ahmed Abdulshafy <abdulshafy@gmail.com> - 2013-05-27 13:11 -0700
        Re: Short-circuit Logic Nobody <nobody@nowhere.com> - 2013-05-28 01:10 +0100
          Re: Short-circuit Logic Ahmed Abdulshafy <abdulshafy@gmail.com> - 2013-05-28 01:39 -0700
            RE: Short-circuit Logic Carlos Nepomuceno <carlosnepomuceno@outlook.com> - 2013-05-28 12:32 +0300
            Re: Short-circuit Logic Mark Lawrence <breamoreboy@yahoo.co.uk> - 2013-05-28 12:45 +0100
            Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-28 13:51 +0000
              Re: Short-circuit Logic Grant Edwards <invalid@invalid.invalid> - 2013-05-28 15:14 +0000
                Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-28 15:55 +0000
        Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-28 13:48 +0000
          Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-29 00:01 +1000
          Re: Short-circuit Logic Ahmed Abdulshafy <abdulshafy@gmail.com> - 2013-05-29 07:27 -0700
            Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-30 00:32 +1000
            Re: Short-circuit Logic rusi <rustompmody@gmail.com> - 2013-05-29 07:33 -0700
              Re: Short-circuit Logic Ian Kelly <ian.g.kelly@gmail.com> - 2013-05-29 10:50 -0600
                Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-30 02:28 +0000
                  Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-30 13:45 +1000
                    Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-30 05:42 +0000
                      Re: Short-circuit Logic Jussi Piitulainen <jpiitula@ling.helsinki.fi> - 2013-05-30 10:22 +0300
                        Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-30 08:29 +0000
                          Re: Short-circuit Logic Jussi Piitulainen <jpiitula@ling.helsinki.fi> - 2013-05-30 12:07 +0300
                            Re: Short-circuit Logic Nobody <nobody@nowhere.com> - 2013-05-30 23:55 +0100
                          Re: Short-circuit Logic Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-05-30 19:31 -0400
                          Re: Short-circuit Logic Stefan Drees <stefan@drees.name> - 2013-05-31 17:34 +0200
                        Re: Short-circuit Logic Roy Smith <roy@panix.com> - 2013-05-30 08:48 -0400
                          Re: Short-circuit Logic Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-05-30 19:38 -0400
                            Re: Short-circuit Logic Nobody <nobody@nowhere.com> - 2013-05-31 02:10 +0100
                              Re: Short-circuit Logic Roy Smith <roy@panix.com> - 2013-05-30 21:21 -0400
                              Re: Short-circuit Logic Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-05-30 21:57 -0400
                              Re: Short-circuit Logic Michael Torrie <torriem@gmail.com> - 2013-05-30 21:33 -0600
                          RE: Short-circuit Logic Carlos Nepomuceno <carlosnepomuceno@outlook.com> - 2013-05-31 03:03 +0300
                      Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-30 18:29 +1000
                      RE: Short-circuit Logic Carlos Nepomuceno <carlosnepomuceno@outlook.com> - 2013-05-31 00:03 +0300
                        Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-31 05:13 +0000
                          RE: Short-circuit Logic Carlos Nepomuceno <carlosnepomuceno@outlook.com> - 2013-05-31 09:42 +0300
                            Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-31 08:11 +0000
                          Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-31 17:09 +1000
                            Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-31 08:45 +0000
                              Re: Short-circuit Logic Roy Smith <roy@panix.com> - 2013-05-31 09:20 -0400
                              RE: Short-circuit Logic Carlos Nepomuceno <carlosnepomuceno@outlook.com> - 2013-06-01 10:23 +0300
                  Re: Short-circuit Logic 88888 Dihedral <dihedral88888@gmail.com> - 2013-05-30 20:11 -0700
              Re: Short-circuit Logic Dave Angel <davea@davea.name> - 2013-05-29 20:23 -0400
                Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-30 05:20 +0000
            Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-30 05:10 +0000
              Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-30 15:22 +1000
                Re: Short-circuit Logic Roy Smith <roy@panix.com> - 2013-05-30 08:40 -0400
                  Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-30 22:58 +1000
                    Re: Short-circuit Logic rusi <rustompmody@gmail.com> - 2013-05-30 09:58 -0700
                      Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-31 03:23 +1000
                      Re: Short-circuit Logic Rick Johnson <rantingrickjohnson@gmail.com> - 2013-05-30 17:13 -0700
                        Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-31 12:29 +1000
                  Re: Short-circuit Logic Ethan Furman <ethan@stoneleaf.us> - 2013-05-30 08:02 -0700
                  Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-31 01:56 +1000
                    Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-30 16:40 +0000
                      Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-30 19:22 +0000
                        Re: Short-circuit Logic Chris Angelico <rosuav@gmail.com> - 2013-05-31 07:46 +1000
                  Re: Short-circuit Logic Ethan Furman <ethan@stoneleaf.us> - 2013-05-30 09:30 -0700
                Re: Short-circuit Logic Neil Cerutti <neilc@norwich.edu> - 2013-05-30 19:30 +0000
                  Re: Short-circuit Logic Ian Kelly <ian.g.kelly@gmail.com> - 2013-05-30 13:49 -0600
    Re: Short-circuit Logic Terry Jan Reedy <tjreedy@udel.edu> - 2013-05-26 16:19 -0400
      Re: Short-circuit Logic Roy Smith <roy@panix.com> - 2013-05-26 16:22 -0400
        Re: Short-circuit Logic Terry Jan Reedy <tjreedy@udel.edu> - 2013-05-26 17:28 -0400
        Re: Short-circuit Logic Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-05-27 00:40 +0000
          Re: Short-circuit Logic Cameron Simpson <cs@zip.com.au> - 2013-05-27 11:57 +1000
          Re: Short-circuit Logic rusi <rustompmody@gmail.com> - 2013-05-26 21:44 -0700
          Re: Short-circuit Logic Vito De Tullio <vito.detullio@gmail.com> - 2013-05-27 06:59 +0200
    Re: Short-circuit Logic Nobody <nobody@nowhere.com> - 2013-05-27 18:52 +0100
    Re: Short-circuit Logic Ahmed Abdulshafy <abdulshafy@gmail.com> - 2013-05-27 13:08 -0700
      Re: Short-circuit Logic Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-05-27 21:36 -0400

Page 4 of 4 — ← Prev page 1 2 3 [4]


#46540

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-05-30 13:49 -0600
Message-ID<mailman.2449.1369943426.3114.python-list@python.org>
In reply to#46536
On Thu, May 30, 2013 at 1:30 PM, Neil Cerutti <neilc@norwich.edu> wrote:
> On 2013-05-30, Chris Angelico <rosuav@gmail.com> wrote:
>> On Thu, May 30, 2013 at 3:10 PM, Steven D'Aprano
>><steve+comp.lang.python@pearwood.info> wrote:
>>> # Wrong, don't do this!
>>> x = 0.1
>>> while x != 17.3:
>>>     print(x)
>>>     x += 0.1
>>
>> Actually, I wouldn't do that with integers either.
>
> I propose borrowing the concept of significant digits from the
> world of Physics.
>
> The above has at least three significant digits. With that scheme
> x would approximately equal 17.3 when 17.25 <= x < 17.35.
>
> But I don't see immediately how to calculate 17.25 and 17.35 from
> 17.3, 00.1 and 3 significant digits.

How about this:

while round(x, 1) != round(17.3, 1):
    pass

The second round call may be unnecessary.  I would expect the parser
to ensure that round(17.3, 1) == 17.3, but I'm not certain that is the
case.

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


#46111

FromTerry Jan Reedy <tjreedy@udel.edu>
Date2013-05-26 16:19 -0400
Message-ID<mailman.2196.1369599562.3114.python-list@python.org>
In reply to#46060
On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:

>       if not allow_zero and abs(x) < sys.float_info.epsilon:
>                  print("zero is not allowed")

The reason for the order is to do the easy calculation first and the 
harder one only if the first passes.


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


#46113

FromRoy Smith <roy@panix.com>
Date2013-05-26 16:22 -0400
Message-ID<roy-31D5CD.16222626052013@news.panix.com>
In reply to#46111
In article <mailman.2196.1369599562.3114.python-list@python.org>,
 Terry Jan Reedy <tjreedy@udel.edu> wrote:

> On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:
> 
> >       if not allow_zero and abs(x) < sys.float_info.epsilon:
> >                  print("zero is not allowed")
> 
> The reason for the order is to do the easy calculation first and the 
> harder one only if the first passes.

This is a particularly egregious case of premature optimization.  You're 
worried about how long it takes to execute abs(x)?  That's silly.

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


#46127

FromTerry Jan Reedy <tjreedy@udel.edu>
Date2013-05-26 17:28 -0400
Message-ID<mailman.2206.1369603740.3114.python-list@python.org>
In reply to#46113
On 5/26/2013 4:22 PM, Roy Smith wrote:
> In article <mailman.2196.1369599562.3114.python-list@python.org>,
>   Terry Jan Reedy <tjreedy@udel.edu> wrote:
>
>> On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:
>>
>>>        if not allow_zero and abs(x) < sys.float_info.epsilon:
>>>                   print("zero is not allowed")
>>
>> The reason for the order is to do the easy calculation first and the
>> harder one only if the first passes.
>
> This is a particularly egregious case of premature optimization.  You're
> worried about how long it takes to execute abs(x)?  That's silly.

This is a particularly egregious case of premature response. You're 
ignoring an extra name lookup and two extra attribute lookups. That's silly.

That's beside the fact that one *must* choose, so any difference is a 
reason to act rather than being frozen like Buridan's ass.
http://en.wikipedia.org/wiki/Buridan%27s_ass

If you wish, replace 'The reason' with 'A reason'. I also the logical 
flow as better with the order given.




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


#46151

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2013-05-27 00:40 +0000
Message-ID<51a2ab67$0$30002$c3e8da3$5496439d@news.astraweb.com>
In reply to#46113
On Sun, 26 May 2013 16:22:26 -0400, Roy Smith wrote:

> In article <mailman.2196.1369599562.3114.python-list@python.org>,
>  Terry Jan Reedy <tjreedy@udel.edu> wrote:
> 
>> On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:
>> 
>> >       if not allow_zero and abs(x) < sys.float_info.epsilon:
>> >                  print("zero is not allowed")
>> 
>> The reason for the order is to do the easy calculation first and the
>> harder one only if the first passes.
> 
> This is a particularly egregious case of premature optimization.  You're
> worried about how long it takes to execute abs(x)?  That's silly.

I don't think it's a matter of premature optimization so much as the 
general principle "run code only if it needs to run". Hence, first you 
check the flag to decide whether or not you care whether x is near zero, 
and *only if you care* do you then check whether x is near zero.

# This is silly:
if x is near zero:
    if we care:
        handle near zero condition()

# This is better:
if we care:
    if x is near zero
        handle near zero condition()


Not only is this easier to understand because it matches how we do things 
in the real life, but it has the benefit that if the "near zero" 
condition ever changes to become much more expensive, you don't have to 
worry about reordering the tests because they're already in the right 
order.



-- 
Steven

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


#46156

FromCameron Simpson <cs@zip.com.au>
Date2013-05-27 11:57 +1000
Message-ID<mailman.2228.1369621763.3114.python-list@python.org>
In reply to#46151
On 27May2013 00:40, Steven D'Aprano <steve+comp.lang.python@pearwood.info> wrote:
| On Sun, 26 May 2013 16:22:26 -0400, Roy Smith wrote:
| 
| > In article <mailman.2196.1369599562.3114.python-list@python.org>,
| >  Terry Jan Reedy <tjreedy@udel.edu> wrote:
| > 
| >> On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:
| >> 
| >> >       if not allow_zero and abs(x) < sys.float_info.epsilon:
| >> >                  print("zero is not allowed")
| >> 
| >> The reason for the order is to do the easy calculation first and the
| >> harder one only if the first passes.
| > 
| > This is a particularly egregious case of premature optimization.  You're
| > worried about how long it takes to execute abs(x)?  That's silly.
| 
| I don't think it's a matter of premature optimization so much as the 
| general principle "run code only if it needs to run". Hence, first you 
| check the flag to decide whether or not you care whether x is near zero, 
| and *only if you care* do you then check whether x is near zero.
| 
| # This is silly:
| if x is near zero:
|     if we care:
|         handle near zero condition()
| 
| # This is better:
| if we care:
|     if x is near zero
|         handle near zero condition()
| 
| 
| Not only is this easier to understand because it matches how we do things 
| in the real life, but it has the benefit that if the "near zero" 
| condition ever changes to become much more expensive, you don't have to 
| worry about reordering the tests because they're already in the right 
| order.

I wouldn't even go that far, though nothing you say above is wrong.

Terry's assertion "The reason for the order is to do the easy
calculation first and the harder one only if the first passes" is
only sometimes that case, though well worth considering if the
second test _is_ expensive.

There are other reasons also. The first is of course your response,
that if the first test fails there's no need to even bother with
the second one. Faster, for free!

The second is that sometimes the first test is a guard against even
being able to perform the second test. Example:

  if s is not None and len(s) > 0:
    ... do something with the non-empty string `s` ...

In this example, None is a sentinel value for "no valid string" and
calling "len(s)" would raise an exception because None doesn't have
a length.

With short circuiting logic you can write this clearly and intuitively in one line
without extra control structure like the nested ifs above.

Cheers,
-- 
Cameron Simpson <cs@zip.com.au>

Who are all you people and why are you in my computer?  - Kibo

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


#46159

Fromrusi <rustompmody@gmail.com>
Date2013-05-26 21:44 -0700
Message-ID<80c667ec-429d-469d-b69f-1b3effc4a0ef@zo5g2000pbb.googlegroups.com>
In reply to#46151
On May 27, 5:40 am, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> wrote:
> On Sun, 26 May 2013 16:22:26 -0400, Roy Smith wrote:
> > In article <mailman.2196.1369599562.3114.python-l...@python.org>,
> >  Terry Jan Reedy <tjre...@udel.edu> wrote:
>
> >> On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:
>
> >> >       if not allow_zero and abs(x) < sys.float_info.epsilon:
> >> >                  print("zero is not allowed")
>
> >> The reason for the order is to do the easy calculation first and the
> >> harder one only if the first passes.
>
> > This is a particularly egregious case of premature optimization.  You're
> > worried about how long it takes to execute abs(x)?  That's silly.
>
> I don't think it's a matter of premature optimization so much as the
> general principle "run code only if it needs to run". Hence, first you
> check the flag to decide whether or not you care whether x is near zero,
> and *only if you care* do you then check whether x is near zero.
>
> # This is silly:
> if x is near zero:
>     if we care:
>         handle near zero condition()
>
> # This is better:
> if we care:
>     if x is near zero
>         handle near zero condition()
>
> Not only is this easier to understand because it matches how we do things
> in the real life, but it has the benefit that if the "near zero"
> condition ever changes to become much more expensive, you don't have to
> worry about reordering the tests because they're already in the right
> order.
>
> --
> Steven

Three points:

3. These arguments are based on a certain assumption: that the inputs
are evenly distributed statistically.
If however that is not so, ie say:
"We-care" is mostly true
and
"x-is-near-zero" is more often false
then doing the near-zero test first would be advantageous

Well thats the 3rd point...

2. Nikalus Wirth deliberately did not use short-circuit boolean
operators in his languages because he found these kind of distinctions
to deteriorate into irrelevance and miss out the more crucial
questions of correctness

1. As Roy pointed out in his initial response to the OP:
"I dont understand your confusion... None of <the above> applies to
your example"
its not at all clear to me that anything being said has anything to do
with what the OP asked!

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


#46162

FromVito De Tullio <vito.detullio@gmail.com>
Date2013-05-27 06:59 +0200
Message-ID<mailman.2229.1369630778.3114.python-list@python.org>
In reply to#46151
Cameron Simpson wrote:

>   if s is not None and len(s) > 0:
>     ... do something with the non-empty string `s` ...
> 
> In this example, None is a sentinel value for "no valid string" and
> calling "len(s)" would raise an exception because None doesn't have
> a length.

obviously in this case an `if s: ...` is more than sufficient :P

-- 
ZeD

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


#46213

FromNobody <nobody@nowhere.com>
Date2013-05-27 18:52 +0100
Message-ID<pan.2013.05.27.17.52.14.263000@nowhere.com>
In reply to#46060
On Sun, 26 May 2013 04:11:56 -0700, Ahmed Abdulshafy wrote:

> I'm having a hard time wrapping my head around short-circuit logic that's
> used by Python, coming from a C/C++ background; so I don't understand why
> the following condition is written this way!>
> 
>      if not allow_zero and abs(x) < sys.float_info.epsilon:
>                 print("zero is not allowed")
> 
> The purpose of this snippet is to print the given line when allow_zero is
> False and x is 0.

I don't understand your confusion. The above is directly equivalent to the
following C code:

	if (!allow_zero && fabs(x) < DBL_EPSILON)
	    printf("zero is not allowed\n");

In either case, the use of short-circuit evaluation isn't necessary here;
it would work just as well with a strict[1] "and" operator.

Short-circuit evaluation is useful if the second argument is expensive to
compute, or (more significantly) if the second argument should not be
evaluated if the first argument is false; e.g. if x is a pointer then:

	if (x && *x) ...

relies upon short-circuit evaluation to avoid dereferencing a null pointer.

On an unrelated note: the use of the "epsilon" value here is
almost certainly wrong. If the intention is to determine if the result of
a calculation is zero to within the limits of floating-point accuracy,
then it should use a value which is proportional to the values used in
the calculation.

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


#46220

FromAhmed Abdulshafy <abdulshafy@gmail.com>
Date2013-05-27 13:08 -0700
Message-ID<e49eb37c-a11f-4280-9aad-82056b30347c@googlegroups.com>
In reply to#46060
On Sunday, May 26, 2013 1:11:56 PM UTC+2, Ahmed Abdulshafy wrote:
> Hi,
> 
> I'm having a hard time wrapping my head around short-circuit logic that's used by Python, coming from a C/C++ background; so I don't understand why the following condition is written this way!>
> 
> 
> 
>      if not allow_zero and abs(x) < sys.float_info.epsilon:
> 
>                 print("zero is not allowed")
> 
> 
> 
> The purpose of this snippet is to print the given line when allow_zero is False and x is 0.

Thank you guys! you gave me valuable insights! But regarding my original post, I don't know why for the past two days I was looking at the code *only* this way>
     if ( not allow_zero and abs(x) ) < sys.float_info.epsilon:

I feel so stupid now :-/, may be it's the new syntax confusing me :)! Thanks again guys.

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


#46245

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2013-05-27 21:36 -0400
Message-ID<mailman.2273.1369704999.3114.python-list@python.org>
In reply to#46220
On Mon, 27 May 2013 13:08:34 -0700 (PDT), Ahmed Abdulshafy
<abdulshafy@gmail.com> declaimed the following in
gmane.comp.python.general:


> Thank you guys! you gave me valuable insights! But regarding my original post, I don't know why for the past two days I was looking at the code *only* this way>
>      if ( not allow_zero and abs(x) ) < sys.float_info.epsilon:
>
	Ah... That's covered under "operator precedence" and not the
short-circuit evaluation rule.

	Boolean "and" and "or" tend to come last in the parsing (bitwise &
and ^ come earlier, as I recall)

{Python 2.x}
>>> 5 & 2
0
>>> 5 ^ 2
7
>>> 5 and 2 
2
>>> 5 or 2
5
>>> 
>>> 5 & 2 and 5 ^ 2
0
>>> 5 & 2 or 5 ^ 2
7
>>> 5 ^ 2 and 5 & 2
0
>>> 5 ^ 2 or 5 & 2
7
>>> 
>>> 5 ^ (2 or 5) & 2
7
>>> 5 ^ (2 and 5) & 2
5
>>> 5 & (2 and 5) ^ 2
7
>>> 5 & (2 or 5) ^ 2
2
>>> 
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
        wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [standalone]


Page 4 of 4 — ← Prev page 1 2 3 [4]

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


csiph-web