我需要创建一个整数的收敛列表,对于任何给定的长度,它都将被排序:
最大,最小,第二大,第二小,第三大,第三小...
直到我们的人数用完。
例如。
def converging_list(val):
lst = some clever function
return lst
converging_list(7)
Output: [7,0,6,1,5,2,4,3]我该怎么做呢?
发布于 2021-02-15 04:44:15
一个非递归的解决方案:
def converging_list(val):
i = 0
j = val
lst = []
while j > i:
lst.append(j)
lst.append(i)
i += 1
j -= 1
if val % 2 == 0: lst.append(i)
return lst
print(converging_list(7))打印
[7, 0, 6, 1, 5, 2, 4, 3]发布于 2021-02-15 04:43:07
您可以使用递归解决方案,使用yield
def converging_list(val, end=0):
if val >= end:
yield val
yield end
yield from converging_list(val-1, end+1)
>>> list(converging_list(7))
[7, 0, 6, 1, 5, 2, 4, 3]如果您不想在函数外部调用函数,只需将其更改为helper list:
def converging_list(val):
def _helper(val, end=0):
if val >= end:
yield val
yield end
yield from _helper(val-1, end+1)
return list(_helper(val))
>>> converging_list(7)
[7, 0, 6, 1, 5, 2, 4, 3]这可以变得更普遍,也就是说,考虑到负值:
def converging_list(val):
def _helper(val, end=0):
sign = 1 if val>0 else -1
if val*sign >= end*sign:
yield val
yield end
yield from _helper(val-1*sign, end+1*sign)
return list(_helper(val))
>>> converging_list(-7)
[-7, 0, -6, -1, -5, -2, -4, -3]发布于 2021-02-15 04:45:09
当长度不为零时,我会尝试在输入元素上执行while循环。在循环中,我将计算当前列表的max和max,将这两个值添加到输出列表中,然后将它们从当前列表中删除。但这是假设没有重复的,是这样的吗?
https://stackoverflow.com/questions/66199839
复制相似问题