为什么这个快速排序会溢出?
Why is this quicksort overflowing?
我有以下 Hy 代码:
(defn quicksort [lst]
(if (< (len lst) 2)
(return lst)
(do
(setv pivot (// (len lst) 2))
(setv (, under same over) (, [] [] []))
(for [i lst]
(if (< i pivot)
(.append under i)
(if (= i pivot)
(.append same i)
(.append over i))))
(return (+ (quicksort under) same (quicksort over))))))
我从这个 Python 函数中大致翻译而来:
def quicksort(lst: list) -> list:
if len(lst) < 2:
return lst
else:
under, same, over = [], [], []
pivot = lst[len(lst)//2]
for i in lst:
if i < pivot:
under.append(i)
elif i == pivot:
same.append(i)
elif i > pivot:
over.append(i)
return (quicksort(under) if under else []) + same + (quicksort(over) if over else [])
但是,Hy 函数抛出以下错误:(在 online Hy 解释器中演示)
RecursionError: maximum recursion depth exceeded while calling a Python object
我是不是调用错了函数?
你写的是(// (len lst) 2)
,但是对应的Python代码相当于(get lst (// (len lst) 2))
.
我有以下 Hy 代码:
(defn quicksort [lst]
(if (< (len lst) 2)
(return lst)
(do
(setv pivot (// (len lst) 2))
(setv (, under same over) (, [] [] []))
(for [i lst]
(if (< i pivot)
(.append under i)
(if (= i pivot)
(.append same i)
(.append over i))))
(return (+ (quicksort under) same (quicksort over))))))
我从这个 Python 函数中大致翻译而来:
def quicksort(lst: list) -> list:
if len(lst) < 2:
return lst
else:
under, same, over = [], [], []
pivot = lst[len(lst)//2]
for i in lst:
if i < pivot:
under.append(i)
elif i == pivot:
same.append(i)
elif i > pivot:
over.append(i)
return (quicksort(under) if under else []) + same + (quicksort(over) if over else [])
但是,Hy 函数抛出以下错误:(在 online Hy 解释器中演示)
RecursionError: maximum recursion depth exceeded while calling a Python object
你写的是(// (len lst) 2)
,但是对应的Python代码相当于(get lst (// (len lst) 2))
.