Mistake in function Definition [duplicate] - python

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 3 years ago.
I've written a fuction with lots of ELIF and OR statements. Code is working, but result is not what i'm expacting to get - absolutly the same values in DF table i'm cooperating with. What am I doing wrong?
def some_func(x):
if x == "aaaa" or "bbb" or "ccc" or "zzz":
return 1
elif x == "ddd" or "eee" or "fff" or "ggg":
return 2
elif x == "hhh" or "ppp" or "nnn" or "mmm":
return 3
else:
return 0
df.TABLE_name = df.TABLE_name.apply(some_func).astype('int64')
df['TABLE_name'].value_counts()
Out: 1 38133

Although your intuition is correct, the way your code is currently set up, it is not executing how you want.
Writing:
if x == "hello" or "world" does not check to see if x is equal to hello or equal to world. It checks to see if x is equal to hello and automatically returns true, because it essentially is evaluating if("hello"), which would always return true
Your code isn't working properly because your syntax is wrong. Consider making these changes:
def some_func(x):
if x == "aaaa" or x == "bbb" or x == "ccc" or x == "zzz":
return 1
elif x == "ddd" or x == "eee" or x == "fff" or x == "ggg":
return 2
elif x == "hhh" or x == "ppp" or x == "nnn" or x == "mmm":
return 3
else:
return 0

Rather than doing multiple O(n) comparisons in each if/elif statement consider using a set for single O(1) comparison instead:
def some_func(x):
if x in {"aaaa", "bbb", "ccc", "zzz"}:
return 1
elif x in {"ddd", "eee", "fff", "ggg"}:
return 2
elif x in {"hhh", "ppp", "nnn", "mmm"}:
return 3
else:
return 0

Related

is there difference between print and return inside a function [duplicate]

This question already has answers here:
Print vs Return in Python Function
(2 answers)
Closed 6 months ago.
I'm doing some Kaggle exercises and the question is asking me to "In the cell below, define a function called sign which takes a numerical argument and returns -1 if it's negative, 1 if it's positive, and 0 if it's 0". This was my function:
def sign(x):
if x < 0:
print('-1')
elif x > 0:
print('1')
else:
print('0')
I tested on VS Code but Kaggle saying it's "incorrect". The proper solution it's the following:
def sign(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
I would like to know what's the real difference between my function and Kaggle's?
Cheers
The difference between print and return is that when you use print, you don`t have to call your function with print, example:
def sign(x):
if x > 0:
print('123')
elif x < 0:
print('134')
else:
print('Hey')
sign(1) # That is how you call your func with no print
Otherwise, if you use returns in your code, than you have to use print when you call your fucn, example:
def sign(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
print(sign(1)) # That is how you call your func with print
Also if you need to get the result value of func, then you can assign a value to a variable, example:
def func(x=0):
x = x ** 2
return x
a = func(5)
print(a) # 25

A problem in python odd or even function. Returning True is not working

def is_even(x) :
while x:
if x==0:
return True
elif x==1:
return False
x-=2
print(is_even(5))
print(is_even(6))
output
False
None
If the x==0 is replace with x==2 it works fine. Please explain why returning True is not working for x==0.
In the last iteration, x is reduced to 0 so the while loop is not entered, and the function is terminated. Since it doesn't explicitly return anything, it implicitly returns None, which is a false-y.
You could use a single if inside the while loop and use the while's condiiton itself to indicate an even number:
def is_even(x) :
while x:
if x==1:
return False
x-=2
return True
If x = 0, then you fail your whilecheck and break out of the loop before you can check if x==0: return True.
You should instead use the modulo function, which returns the remainder of division.
3 % 2 == 1 # Odds
5 % 2 == 1
7 % 2 == 1
2 % 2 == 0 # Evens
4 % 2 == 0
6 % 2 == 0
Because when x == 0 it fails your while x check (0 is not truthy), so it exits the loop before it checks your condition again.
BTW the normal way to check parity is with the modulus (%) operator.
x % 2 == 0 # is_even
x % 2 != 0 # is_odd
If you use x as a condition while x that condition will be False if x equals 0.
The correct way should be:
def is_even(x):
while True:
if x==0:
return True
elif x==1:
return False
x-=2
Obviously this is a very weird way to check if a number is even, you can do:
def is_even(x):
return not bool(x%2)
In Python, integers have True and False values. Any integer that is not 0, will always evaluate True, and 0 will evaluate False.
In your code you are using a while loop, which only runs if the subsequent statement evaluates True. When you check while x, if the value of x is 0 (due to the calculation inside the loop), your statement will be the same as while False, which will not run the code inside.
To avoid this issue you can use the modulo operation, which gives you the remainder of an operation. Hence, x % 2 will return 0, if x is even, and 1 if it is odd. You can make a check on that and return the correct value in fewer lines, using fewer operations.
return (x % 2 == 0)
The above statement will return True if there is no remainder, and False if there is.
This should work
def is_even(x):
while x>=0:
if x == 0:
return True
elif x == 1:
return False
x -= 2
print(is_even(5))
print(is_even(6))
in your code the loop terminates when x reaches 0, put a condition such that the loop runs even when x is 0
cheers

function return none instead of return number

I create a function that compare with x and y variable. Inside the function has a lots of nested elif to compare the x and y then return integer. The problem is right now, when it runs at the certain elif statement, it didn't execute the statement although the statement is correct.
def convertTo(self, x, y):
if( x == 0 & y == 0):
return 0
if( x == 0 & y == 1):
return 1
if( x == 0 & y == 2):
return 2
if( x == 0 & y == 3):
return 3
if( x == 1 & y == 0):
return 4 # Didn't return this line even though x = 1 and y = 0
else
return None
def main():
self.convertTo(0,0)
self.convertTo(0,1)
self.convertTo(0,2)
self.convertTo(0,3)
self.convertTo(1,0) # return None? Why?
You're performing a chained equality comparison which is not doing what you think it does. The bitwise & is performed first as it has a higher priority than ==.
Replace:
x == 1 & y == 0
# 1 == 1 & 0 == 0
# 1 == 0 == 0 False!
With:
x == 1 and y == 0
See: Operator precedence
In Python, "&" and "and" do two different things. "and" is what you should be using, "&" is a binary operator.
if
a = 0011 1100
and
b = 0000 1101
then
a&b = 0000 1100
See http://www.tutorialspoint.com/python/python_basic_operators.htm
You should use and instead of &, as & is a bitwise and.
Chaining multiple conditions in Python is generally done with an if-elif-else statement like below:
if a and b:
# a and b both was true
elif a and not b:
# a was true, but b wasn't
else:
# none of the conditions matched
In your code, if it wasn't for the return statement in each if, and the fact that you are checking the same two variables, it would be possible for two if statements to evaluate to true.
if a:
# this will run if a was true
if b:
# regardless of a this will run if b was true
else:
# regardless of a this will only run if b was false
Also, take a look at this: https://docs.python.org/3/tutorial/controlflow.html

Don't understand why if statement fails. Function to find prime number [duplicate]

This question already has answers here:
Python, prime number checker [duplicate]
(3 answers)
Closed 7 years ago.
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(2, x):
if x % i == 0:
return False
else:
return True
This doesn't work for number 9, where it returns true.
Please explain in basic terms.
You have to remove the else condition in the for loop. For example: for the input: 9 when execution enters the for loop the condition checked is 9 % 2 == 0. Since, it is False, the execution will continue to the else part and will return the value True. What it did not do is continue checking the divisibility with the other numbers. Hence, if the condition is not True, it should simply continue checking divisibility with the other numbers.
Code:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(2, x):
if x % i == 0:
return False
return True

If..else works as OR, does it true?

Does if..elif statements works exactly as one OR statement?
For example does below if..elif:
if X == "a":
Y = 1
elif Z == "b" and V = "c":
Y = 1
Works as
if X == "a" or (Z == "b" and V == "c"):
Y = 1
Yes, in your specific case the functionality is the same. You would use an if/elif statement if you were going to do two different things based upon the condition which executes to True. For example,
if a == 'a':
y = 1
elif z == 'b' and v == 'c':
y = 2
However, since in both cases you are doing Y = 1, then
if x == 'a' or (z == 'b' and v == 'c'):
y = 1
works just fine and even is more appropriate.
The effect in your code is the same. But it doesn't work the same way. The or statement looks at the two statements and will return True if at least one of the statements are true. On the other hand, the if...elif statement would just go into one of the conditions. Either only into the if statement, or only into the elif statement.

Categories

Resources