【发布时间】:2017-07-17 12:29:38
【问题描述】:
second_smallest(input_list) 函数必须从嵌套列表的列表中返回第二小的值。函数不得多次通过列表(不能展平然后继续),必须使用默认的内置 python 函数(no import),必须使用递归和没有循环。传入函数的列表可以是以下形式:
>>> [1,2,3]
>>> [[1,2],3]
>>> [[1],2,3]
>>> [[],1,2,3]
>>> [[1],[2],[3]]
>>> [1,2,3,2,[4,5],[]]
所以 input_list 可以是所有这些形式,所有这些形式的返回应该是 2
>>> [1,1,2,3]
将返回 1
>>> second_smallest([[1],[2]])
有效,但是
>>> second_smallest([1])
不是
我目前拥有的是这样的:
def second_smallest(numbers):
'''(list of int) -> int
This function takes in 1 parameter, input_list, and returns the second
smallest number in the list.
'''
# if the length of numbers is equal to 2, then set result equal to the
# second element if the first is less than or equal to second, otherwise
# set result equal to the first element
if(len(numbers) == 2):
if(numbers[0] <= numbers[1]):
result = numbers[1]
else:
result = numbers[0]
# if the length of numbers is greater than 2, then set result equal to
# second_smallest_help of the first to second last element in numbers if
# first is less than or equal to last and last is greater than or equal to
# second, otherwise, set result equal to second_smallest of the last to the
# second last
else:
if(numbers[0] <= numbers[-1] >= numbers[1]):
result = second_smallest(numbers[:-1])
else:
result = second_smallest([numbers[-1]] + numbers[:-1])
return result
但此代码仅适用于非嵌套列表。那么我该如何调整我的实现(或完全改变)以解决这个问题?
我想到的一种方法是检查当前块的递归深度,有没有办法做到这一点?
【问题讨论】:
-
您还可以使用生成器将其展平。那么你仍然只会通过它一次;-)
-
附上声明,
numbers[-1] + numbers[:-1]无论如何你都没有将列表展平吗? -
我当前的函数只适用于非嵌套列表,所以你的问题是无关紧要的。
标签: python list recursion nested