def accumulate(fn, initial, seq):
if seq == ():
return initial
else:
return fn(seq[0], accumulate(fn, initial, seq[1:]))
我假设使用accumulate
编写一个排序函数。
def insertion_sort_hof(tup):
return accumulate(lambda x,y: x,y = y,x if x > y else None , () ,tup)
这是我的代码,我似乎无法运行它。为什么?
insertion_sort_hof(()) # ()
insertion_sort_hof((19,10,1,4,3,1,3, 2)) #(1, 1, 2, 3, 3, 4, 10, 19)
lambda不能包含赋值,因此您的lambda无效。试着添加这样的括号,你会得到一条错误消息:
lambda x,y: (x,y) = (y,x) if x > y else None
无论如何,它都不起作用,因为您只需要将值本地交换到该函数。