编写 return 函数
Writing the return function
这是我的代码:
def issorted(numlist):
sortbool = True
for i in range(1, len(numlist)):
if numlist[i] < numlist[i-1]:
sortbool = False
if True:
return(not sortbool)
return(sortbool)
如何至少再添加一个 return 语句?这样一来,当检测到本地违反排序顺序要求时,它可以过早地中止该函数。
给出的输出示例是:
>>> print(issorted([3, 4, 5.0, 7]))
True
>>> print(issorted([-1, 8, -3, 8]))
False
>>> print(issorted([1]))
True
>>> print(issorted([]))
True
谨慎使用变量。有时它们很有用,有时它们会让你感到困惑。
def issorted(numlist):
for i in range(1, len(numlist)):
if numlist[i] < numlist[i-1]:
#you want to return False and exit the function.
#return is the best option here.
return False
#if the for loop succeeds, you want to return True by default
return True
只是return一个常量;这里不需要变量,您会完全困惑。您的代码:
if numlist[i] < numlist[i-1]:
sortbool = False
if True:
return(not sortbool)
总是 returning True
,因为你将 sortbool
设置为 False
,但是 return not sortbool
(所以不是False
,即 True
),True
值为真,总是。
只要在列表中找到值小于前一个值的位置,您的代码就应该return False
,否则return True
;只需将这些值硬编码为文字:
def issorted(numlist):
previous = numlist[0]
for value in numlist:
if value < previous:
# the current value is smaller than the previous,
# so the list is not (forward) sorted. Exit with False
return False
previous = value
# all values were equal or larger than their predecessors, so
# the list is sorted, exit with True
return True
请注意,我在那里玩了个小把戏;我使用一个额外的变量来跟踪以前的值而不是生成索引。
这是我的代码:
def issorted(numlist):
sortbool = True
for i in range(1, len(numlist)):
if numlist[i] < numlist[i-1]:
sortbool = False
if True:
return(not sortbool)
return(sortbool)
如何至少再添加一个 return 语句?这样一来,当检测到本地违反排序顺序要求时,它可以过早地中止该函数。
给出的输出示例是:
>>> print(issorted([3, 4, 5.0, 7]))
True
>>> print(issorted([-1, 8, -3, 8]))
False
>>> print(issorted([1]))
True
>>> print(issorted([]))
True
谨慎使用变量。有时它们很有用,有时它们会让你感到困惑。
def issorted(numlist):
for i in range(1, len(numlist)):
if numlist[i] < numlist[i-1]:
#you want to return False and exit the function.
#return is the best option here.
return False
#if the for loop succeeds, you want to return True by default
return True
只是return一个常量;这里不需要变量,您会完全困惑。您的代码:
if numlist[i] < numlist[i-1]:
sortbool = False
if True:
return(not sortbool)
总是 returning True
,因为你将 sortbool
设置为 False
,但是 return not sortbool
(所以不是False
,即 True
),True
值为真,总是。
只要在列表中找到值小于前一个值的位置,您的代码就应该return False
,否则return True
;只需将这些值硬编码为文字:
def issorted(numlist):
previous = numlist[0]
for value in numlist:
if value < previous:
# the current value is smaller than the previous,
# so the list is not (forward) sorted. Exit with False
return False
previous = value
# all values were equal or larger than their predecessors, so
# the list is sorted, exit with True
return True
请注意,我在那里玩了个小把戏;我使用一个额外的变量来跟踪以前的值而不是生成索引。