英文:
Simplifying if(condition): return True to one line return statement changes results in Python
问题
I do not understand why the two methods written below perform differently. Any insights into why the simplified statement in xyz_there() fails for this test case would be appreciated!
str = "abcxyz"
def xyz_there(str):
for i in range(len(str)):
return (str[i:i+3] == 'xyz' and str[i-1] != '.')
return False
def xyz_there2(str):
for i in range(len(str)):
if str[i:i+3] == 'xyz' and str[i-1] != '.':
return True
return False
print(xyz_there(str))
print(xyz_there2(str))
It has always been my understanding that the return(condition)
was the most efficient way to write that expression. I am aware that functions like find()
and count()
can also be used to solve this problem.
英文:
I do not understand why the two methods written below perform differently. Any insights into why the simplified statement in xyz_there() fails for this test case would be appreciated!
str = "abcxyz"
def xyz_there(str):
for i in range(len(str)):
return (str[i:i+3] == 'xyz' and str[i-1] != '.')
return False
def xyz_there2(str):
for i in range(len(str)):
if str[i:i+3] == 'xyz' and str[i-1] != '.':
return True
return False
print(xyz_there(str))
print(xyz_there2(str))
It has always been my understanding that the return(condition) was the most efficient way to write that expression. I am aware that functions like find() and count() can also be used to solve this problem.
答案1
得分: 1
欢迎来到stackoverflow!
这两个函数之间的区别在于,在第二个函数xyz_there2
中,return True
语句位于if
语句内部,因此只有在条件为真时才执行。如果条件不成立,循环会继续到下一个i
的值。
然而,在第一个函数xyz_there
中,return
语句不位于任何if
语句内部,因此它在循环的第一次迭代中执行,从而返回False
值。之后函数退出,循环没有机会迭代到下一个i
的值。
换句话说,xyz_there
函数在第一次循环迭代时返回False
,当i==0
时。而xyz_there2
会迭代直到i==3
,然后返回True
。
英文:
Welcome to stackoverflow!
Difference between these two functions is that in second function, xyz_there2
, the return True
statement is inside if
, so it is executed only if the condition is true. If it is not true - loop continues to next value of i
.
However, in first function xyz_there
, the return
statement is not inside of any if
statement, so it's executed on first iteration of the loop, thus returning False
value. And after that the function exits, and loop doesn't get a chance to iterate to next value of i
.
In other words, xyz_there
function returns False
at first loop iteration, when i==0
. While xyz_there2
iterates until i==3
, and returns True
.
答案2
得分: 0
你的第一个函数等同于以下代码,它返回 False:
def xyz_there(str):
return (str[0:3] == 'xyz' and str[-1] != '.')
因为你没有遍历字符串中的所有字符,而只是对单词的前三个字母做出决定并返回结果。
英文:
your first function is equivalent to this which is returning Flase :
def xyz_there(str):
return (str[0:3] == 'xyz' and str[-1] != '.')
because you are not looping through all the characters in the string , you are just making decision on the first 3 letters of the word and return it
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论