查找第一个顺序错误的Python的递归代码
我写了两个代码,迭代的和递归的,它们应该返回比最后一个小的第一个数字,即列表中第一个顺序错误的数字 迭代代码,运行良好:查找第一个顺序错误的Python的递归代码,python,Python,我写了两个代码,迭代的和递归的,它们应该返回比最后一个小的第一个数字,即列表中第一个顺序错误的数字 迭代代码,运行良好: def out_of_order(lst): before = 0 for y in lst: if y < before: return y before = y print(out_of_order([1,5,17,12,24])) 我认为这至少可以取代: lst1=lst[1:len(st
def out_of_order(lst):
before = 0
for y in lst:
if y < before:
return y
before = y
print(out_of_order([1,5,17,12,24]))
我认为这至少可以取代:
lst1=lst[1:len(str)]
与:
如果您使用str作为调试工具,并且在删除它之后忘记修改代码,那么它就会起作用
注释:你不应该假设列表中至少有两个项目,如果第一个是
您可以使用Python 2.5以后版本中使用的条件语法
def out_of_orders(lst):
return lst[1] if (lst[1] < lst[0]) else out_of_orders(lst[1:])
当然,您必须测试子数组是否按正确顺序缩小所有内容,因此完整示例如下:
lst = [1,5,17,12,24]
def out_of_orders(lst):
if len(lst) == 1:
return None
return lst[1] if (lst[1] < lst[0]) else out_of_orders(lst[1:])
print out_of_orders(lst)
虽然不是在所有情况下,但递归代码确实会运行。您有几个问题:
def out_of_orders(lst):
if(lst[1]<lst[0]): # what if len(lst) < 2?
print(lst[1]) # why print the number...
return # ... then return nothing?
else: # why 'else' - if the 'if' was met, you've already returned
lst1=lst[1:len(lst)] # no need to assign this one line before using it
out_of_orders(lst1) # call recursively but ignore value returned
其中切片[1:]表示从索引1开始,直到用完为止。请注意,这将返回第一个无序编号,或者不返回。用法示例:
>>> print(out_of_order([1, 2, 3]))
None
>>> print(out_of_order([1, 3, 2]))
2
>>> print(out_of_order([3, 1, 2]))
1
现在,调用者可以决定是打印值,还是在进一步的计算中使用它
此外,您的迭代版本在边缘情况下存在问题,请考虑:
>>> out_of_order([-3, -2, -1])
-3
一个可能的解决方案:
def out_of_order(lst):
before = None
for y in lst:
if before is not None and y < before:
return y
before = y
您需要一个lenlst==1的基本情况,否则您的代码将抛出一些错误。什么不起作用?我能看到明显的打字错误,那你为什么不提呢?!你做了什么来弄清楚?你得到了什么样的输出或错误?标签的使用不一致。如果没有任何东西出了问题,它会返回?您还没有编写迭代变量。。。我只需要得到一个字符串到函数out_of_orders[1,2,3,4,5,6,7,4,8,9]
lst = [1,5,17,12,24]
def out_of_orders(lst):
if len(lst) == 1:
return None
return lst[1] if (lst[1] < lst[0]) else out_of_orders(lst[1:])
print out_of_orders(lst)
def out_of_orders(lst):
if(lst[1]<lst[0]): # what if len(lst) < 2?
print(lst[1]) # why print the number...
return # ... then return nothing?
else: # why 'else' - if the 'if' was met, you've already returned
lst1=lst[1:len(lst)] # no need to assign this one line before using it
out_of_orders(lst1) # call recursively but ignore value returned
def out_of_order(lst):
"""Return the first number in lst that's out of order."""
if len(lst) > 1:
if lst[0] > lst[1]:
return lst[1]
return out_of_orders(lst[1:])
>>> print(out_of_order([1, 2, 3]))
None
>>> print(out_of_order([1, 3, 2]))
2
>>> print(out_of_order([3, 1, 2]))
1
>>> out_of_order([-3, -2, -1])
-3
def out_of_order(lst):
before = None
for y in lst:
if before is not None and y < before:
return y
before = y