I asked myself if it makes a performance difference if I use an if statement with x conditions, or x if statements with only 1 condition each.
so for example:
if statement with 3 conditions:
if a == 0 and b == 0 and c == 0:
#do something
3 if statements with just one condition each:
if a == 0:
if b == 0:
if c == 0:
#do something
Why do I want to know this?
I have an if statement with around 30 conditions and my code gets really messi, so I thought about splitting my if-statement in half.
I think that the results of this examples will be the same, but I don't know if there would be a noticeable performance difference if a == 1. Would the program check all 3 conditions in the first example even if the first one (a is 1 not 0) is false?
With the given example, there won't be any difference in performance, even with if a == 0 and b == 0 and c == 0: it won't check b == 0 when the initial condition a == 0 itself is False. But considering the minimal lines of code & readability, if a == 0 and b == 0 and c == 0: would be the better option.
You can test the performance of your script using the timeit library. I will add an example below.
import timeit
stmt1 = 'if a == 0 and b == 0 and c == 0: pass'
stmt2 = """\
if a == 0:
if b == 0:
if c == 0:
pass
"""
setup1 = 'a, b, c = 0, 0, 0'
setup2 = 'a, b, c = 1, 0, 0'
print(f"First statement First setup execution time = {timeit.timeit(stmt=stmt1, setup=setup1, number=10**9)}")
print(f"First statement Second setup execution time = {timeit.timeit(stmt=stmt1, setup=setup2, number=10**9)}")
print(f"Second statement First setup execution time = {timeit.timeit(stmt=stmt2, setup=setup1, number=10**9)}")
print(f"Second statement Second setup execution time = {timeit.timeit(stmt=stmt2, setup=setup2, number=10**9)}")
Output:
First statement First setup execution time = 38.7665075
First statement Second setup execution time = 15.4141367
Second statement First setup execution time = 38.29726529999999
Second statement Second setup execution time = 15.527892699999995
This shows that there is negligible difference to how you format your if statement. But if the first condition is false then the rest of the conditions will not be checked and the execution of the code will run faster.
Edit:
Also after seeing wjandrea comment below I would like to add it to the answer if anyone in the future is wondering why this is. Per the python wiki you can read about short-circuiting operator behavior.
Any time difference between your two pieces of code is complete and total noise. Run your code a billion times, and the amount of time you might save between running one or the other is less than the time it took me to write these two sentences.
Seriously, if you need to be worried about the difference in time between the two pieces of code, Python is the wrong language.
Yes! I think there is an increase of productivity/performance if you can write your code in one line, since often times it can be easier to read and interpret; and even more so if you use descriptive variables.
In your code, I see some things that can be improved: There is what we call the (1) assignment operator, i.e. the equal(=) sign; and (2) The comparison operator, i.e. the "is equal to" (==) sign, "is greater than" (>), "is less than" (<), and etc.
When we define a variable, we use the assignment operator (=) sign. e.g:
a = 0
b = 0
c = 0
On the other hand, we use the comparison operator (such as the (==) symbol) when we make conditional statements. e.g:
if a == 0 and b == 0 and c == 0:
# do something
On to your second question: Would the program check all 3 conditions in the first example even if the first one (a is 1 not 0) is false?
a = 1
b = 0
c = 0
if a == 0:
if b == 0:
if c == 0:
# do something
Python will compare the conditions to your assigned variables, and if the condition turns out to be False, then there will be no ERROR, but it will also not execute the instruction that you've provided in your if-statement (meaning: it will not # do something).
I hope I had help you even a little bit.
Related
I have some variables A and B and I want to check them for a value and if both are False, the function shall render True:
if ( A == 1 and B == 2 ) == False :
do magic
I breaks down if either A or B is not defined and when I test it with
print(A == 1 and B == 1)
this breaks with an error:
IndexError: list index out of range
A or B are actually some variables from web-API and this whole thing runs in a loop, constantly checking and can be either set or not set with a value.
Is there a way to ignore whether A or B is defined or yield a default FALSE if not defined/existing?
Thanks heaps to #iBug
My solution is to check if there is anything in the list and then check if there is the desired element in the list:
'Yes' if fruit == 'Apple' else 'No'
client.futures_get_open_orders()[0]['side'] == 'BUY' if `client.futures_get_open_orders() == True else False`
Just had to sleep and drink 3 coffee in succession next morning :D
See: Putting a simple if-then-else statement on one line
Having trouble understanding Boolean expression for factoring out 0.
x,y=24,36
LCM=1
counting=True
while counting:
if (LCM%x and LCM%y) == 0:
print('The LCM is {}'.format(LCM))
break
LCM+=1
LCM evaluates to 24, which is false
But this code gives the correct LCM:
x,y=24,36
LCM=1
counting=True
while counting:
if LCM%x==0 and LCM%y == 0:
print('The LCM is {}'.format(LCM))
break
LCM+=1
LCM is 72, this is correct
Now why can 0 not be factored out? Generally if I type something like 2 and 3 == 0, the expression evaluates to false, but shouldn't syntax work similarly in the example above. So I getting confused.
In python, 0 == False evaluates to True. So (LCM%x and LCM%y) == 0 evaluates to True when the condition (LCM%x and LCM%y) is False. When does that happen? Whenever either of the values LCM%x or LCM%y is zero.
In your second example, you have LCM%x==0 and LCM%y == 0 which evaluates to True only if both LCM%x and LCM%y are zero.
Because here' it's happening like a binary operation and not as a logical check statement
(0 and 1) = 0 when LCM = 24
if (LCM%x and LCM%y) == 0:
This is happening because the values are 0 and 1 here(Python mistook it for a binary operation but you wanted something else).
If it is like (24 and 36) then it would return the max of two! So be careful when you give conditions to Python/any language!
But here it is the value check like is LCM divisible by x like
if LCM%x==0 and LCM%y == 0:
is 24%24 == 0? and is 36%24 ==0 ?
PS : Use the default Python IDLE, it will give you a clearer view in such simple operations!
Can someone please explain to me how this piece of recursive code is working? Because there is only one if statement which checks if variable x is equal to zero and returns true if the value is equal to zero.
And the other part is just upon calling each other.
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_odd(17)) # outputs true
print(is_even(23)) # outputs false
This pair of mutually recursive functions makes use of three facts:
0 is even
x is even if x - 1 is odd.
x is odd if x - 1 is even.
1 is odd because 1 - 1 == 0 is even.
2 is even because 2 - 1 == 1 is odd.
And so on.
This is not an efficient way to determine if an arbitrary value n is even or odd, but it is a logically correct way. (Assuming the argument is always a natural number, anyway. Passing a negative integer as an argument to either results in infinite recursion, as the base case will never be reached.)
I want to give a simpler answer to follow along with. Think about the stack trace. I'll abbreviate is_even and is_odd as IE and IO respectively.
IO(17)
NOT[IE(17)]
NOT[IO(16)]
NOT[NOT[IE(16)] = IE[16]
IO(15)
...
This is basically checking if alternating descending numbers starting from the input value are even and odd all the way down to 0. Note that if we start with a true statement (like IO(17)) then every line contains a true statement - if we started with a false statement, every line ends up with a false statement. Following the pattern we see here, we see that the final state can therefore end up as
IE(1) -> IO(0) -> NOT[IE(0)] = NOT[True] = False # as expected!
OR
IO(1) -> NOT[IE[1]] = NOT[IO[0]] = NOT[NOT[IE(0)] = NOT[NOT[True]] = True # likewise!
I got a bit stuck with a for loop - what I can see it is doing appears correct but isn't exactly what I'm trying to accomplish with it. I've come from a C background but any advice here would be beneficial.
def deal(player_num, cards):
a = 0
z = 0
i = 0
b = 0
c = player_num
hand = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for a in range(player_num):
hand[a] = cards[i] + cards[i+b+c]
b == b+1
i == i+1
z == z+1
return hand
So the for a in range(player_num) seems to be working (appends a++) but hand[0], hand[1], etc. gets the same hand. I guess it loops a but not the other variables, so I need to use more than 1 nested loop to get i++, b++ and c++?
b == b+1 is a logical expression (returning False every time), not an assignment. I'm guessing you want something like: b += 1
== is the equality operator in Python. = is the assignment operator.
== checks whether its left operand and its right operand are equal and return True or False accordingly. b and b+1 will never be equal to each other and either way it does not make sense to perform an operation without side-effect (like comparing two values for equality) and then do nothing with its result.
If you want to change the values of your variables, use the assignment operator = instead of ==.
Assignment:
Return the number of occurrences of character c in string s,
ignoring case. Use loops. Do not use the in-built string method count,
which does a similar thing. The idea is to learn to write loops. You
should ignore case when comparing a character of s with c.
My attempt:
def countletter(s, c): #BAD
count = 0
for c in s:
if c == c:
count += 1
return count
Am I on the right track? I seem to get some assertion errors when I test it in the main...
your return is at wrong place. So your function is actually returning only after one iteration.
Also you should not use the variable name c in for loop, use some different variable, as it replaces the value of c recieved from the function call with the current character being fetched by the for-loop.
def countletter(s, c): #BAD
count = 0
for x in s:
if x.lower() == c.lower():
count += 1
return count
print countletter("abcdefFf","F") #prints 3
print countletter("a","A") #prints 1
In addition to the answers above, there is a built-in method count in Python. You can use it in your project, if this function isn't a homework etc.(Oh, i saw now, it is an homework. But additional information is harmless.:) )
"baris".count("b")
returns 1
If you compare the variable c defined by for c in s: you are always going to get true. So, your comparison should look like c == 'c' (you can figure out how to do the case insensitive check) and your return is indented incorrectly
The position of the return statement is wrong. Delete the four spaces (or a tab what you've used)
Just as another example of a way to do this outside of the built-in count() method, one can use a generator expression and the sum() builtin:
>>> def countletter(s, c):
... return sum(x.lower() == c.lower() for x in s)
...
>>> countletter("abcdefFf", "F")
3
>>> countletter("a", "A")
1
What we do is produce a generator of True and Falses (True where the character matches). sum() will then give us the count, as True is 1 in Python, and False is 0:
>>> True == 1
True
>>> False == 0
True