Why Order Matters in an 'and' Statement

  • Context: Python 
  • Thread starter Thread starter Taylor_1989
  • Start date Start date
  • Tags Tags
    Python
Click For Summary

Discussion Overview

The discussion revolves around a coding problem related to string manipulation in Python, specifically focusing on the behavior of logical 'and' statements and their evaluation order. Participants explore the implications of shortcut evaluation in conditional statements and consider optimization techniques for the code provided.

Discussion Character

  • Technical explanation
  • Exploratory
  • Conceptual clarification

Main Points Raised

  • One participant describes encountering an "IndexError" when changing the order of conditions in an 'and' statement, leading to a question about why order matters.
  • Another participant explains that many programming languages implement "shortcut" evaluation, where if the first condition is false, the second condition is not evaluated, which can prevent errors like the one encountered.
  • A suggestion is made that the participant might achieve their goal more simply by using the split method on the string.
  • Further optimization suggestions include using string slicing instead of concatenation for better performance and recommending more descriptive variable names for clarity.

Areas of Agreement / Disagreement

Participants generally agree on the concept of shortcut evaluation in programming, but there is no consensus on the best approach to the coding problem, as different optimization techniques and variable naming conventions are suggested without a definitive resolution.

Contextual Notes

Participants discuss the limitations of the original code and the potential for optimization, but do not resolve all assumptions regarding the intended functionality of the code or the best practices for variable naming.

Who May Find This Useful

This discussion may be useful for individuals learning Python programming, particularly those interested in string manipulation, logical conditions, and code optimization techniques.

Taylor_1989
Messages
400
Reaction score
14
TL;DR
I am slightly confused as to why, in a IF statment that when using the AND operator the order in which the operator matters.
I am currently doing a leet code problem and came across something, I have not noticed before.

Here is a sample of the code I am working on.

Python:
s = "10#11#12"
A=[]
B=[]
i=0
count=0
while i < len(s):
    if i+2<len(s) and s[i+2]=='#':
        A+=[(s[i]+s[i+1]+s[i+2])]
        i+=3
        print(i)

Now the code above throws no error, however when I change the order of the and statement like the code below:

Python:
s = "10#11#12"
A=[]
B=[]
i=0
count=0
while i < len(s):
    if s[i+2]=='#' and  i+2<len(s) :
        A+=[(s[i]+s[i+1]+s[i+2])]
        i+=3
        print(i)

I get an out of range error as shown below:
Traceback (most recent call last):
File "<string>", line 10, in <module>
IndexError: string index out of range

So my question is why does order matter? I have always been under the impression that if you had an and statement with two True conditions then it would carry through the if statement, and if one of the conditions was False did not matter which way round it was it would not carry through the if statement.

I now assume this type of thinking is wrong.
 
Technology news on Phys.org
Many (not all) languages implement "shortcut" evaluation of if conditions. If you do a test like IF A AND B THEN, and it turns out that A is FALSE, then there's no point in even checking B - we know A AND B is FALSE whatever it is. So the computer can shortcut the operation. Ditto A OR B if A is TRUE - there's no point checking B in this case.

Knowing this, can you see why your first version works and your second one errors out?
 
  • Like
Likes   Reactions: sysprog, DrClaude, .Scott and 2 others
Incidentally, is what you are trying to achieve here just A=s.split("#")? This isn't what your code does, but I suspect it might be what you are aiming at.
 
Ibix said:
Many (not all) languages implement "shortcut" evaluation of if conditions. If you do a test like IF A AND B THEN, and it turns out that A is FALSE, then there's no point in even checking B - we know A AND B is FALSE whatever it is. So the computer can shortcut the operation. Ditto A OR B if A is TRUE - there's no point checking B in this case.

Knowing this, can you see why your first version works and your second one errors out?
Ah okay, I can see now thank you. Also, I am not aiming at splitting the given string. Basically I have to use a dictionary to convert there given string to a bunch of letter i.e decrypt the message, in this case, a-i is given the numbers 1-9 and j-z onwards is given by 10#, 11#,12#, etc.

I was just playing around with the idea of separating each of these into a list than checking against a dictionary, then from there looking at ways to optimize it the code.
 
Ah - I see. You can definitely optimise that, but I'll leave you to explore.

A couple of points, though. First, s[i]+s[i+1]+s[i+2] can be written s[i:i+3]. That becomes a huge saving when you want s[i:i+50]! Second, can I suggest more descriptive variable names? s for string isn't bad, but encryptedString would be better. And almost anything is better than A and B. Perhaps encryptedChars and decryptedChars?

Side note - my phone's autocomplete dictionary has "encrypted" but not "decrypted". Weird...
 
  • Like
Likes   Reactions: sysprog, jim mcnamara and Taylor_1989
Ibix said:
Ah - I see. You can definitely optimise that, but I'll leave you to explore.

A couple of points, though. First, s[i]+s[i+1]+s[i+2] can be written s[i:i+3]. That becomes a huge saving when you want s[i:i+50]! Second, can I suggest more descriptive variable names? s for string isn't bad, but encryptedString would be better. And almost anything is better than A and B. Perhaps encryptedChars and decryptedChars?

Side note - my phone's autocomplete dictionary has "encrypted" but not "decrypted". Weird...

First thank for the input, I can't believe I didn't think of using a slice method, thank you. To be honest I am just doing the leetcode problems, not for interview practice but more to learn about the python language itself. Also yes I agree my variable names should be more descriptive make sure of this next time
 
  • Like
Likes   Reactions: sysprog, Ibix and jim mcnamara

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 29 ·
Replies
29
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
55
Views
7K
  • · Replies 6 ·
Replies
6
Views
3K
Replies
3
Views
3K
Replies
12
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K