我正在试图制作一个名为median
的程序,它取得一个列表的中间值。如果列表是偶数,那么我将返回两个中间数字。我的头脑中有所有想到的逻辑,但我不知道如何完成它。注:我试图避免使用list-ref,因为它会使问题微不足道。 到目前为止,我的代码如下所示。返回列表中值的方法? (方案)
(define (median lst)
(if (null? lst)
'()
(if (even? lst) ; ends here
现在,我对这个问题的方法是这样的。
Odd #- Return the value of the "car#" that's in place of (/ (+ (length lst) 1) 2)
3; 2nd car (1 100 3) => 100
5; 3rd car (1 2 100 4 5) => 100
7; 4th car (1 2 3 100 5 6 7) => 100
Even # - Return the value of the "car#" that's in place of (/ (length lst) 2) AND (+ (/ (length lst) 2) 1)
2; 1st and 2nd car (1 2) => 1 2
4; 2nd and 3rd car (1 20 30 4) => 20 30
不过,我似乎无法拿出,可以递归实现这个伪代码的方式。
编辑:不确定是否有人仍然在那里愿意帮助,但我最终编写了一个迭代过程,将采取任何奇数列表的中值索引值。我现在的麻烦是实施东西,这将使该代码工作的,甚至列表,也未尝没有在列表返回值:
(define (median-index-odd lst)
(define (median-index-iter1 lst times_carred)
(if (null? lst)
'()
(if (= times_carred (/ (+ (length lst) 1) 2))
(list (car lst))
(median-index-iter1 (cdr lst) (+ 1 times_carred)))))
(median-index-iter1 lst 0))
我也想出了一个单独的程序找到当名单是偶数时的中值指数:
(define (median-index-even lst)
(define (median-index-iter2 lst times_carred)
(if (null? lst)
'()
(if (= times_carred (/ (length lst) 2))
(list (car lst) (cadr lst))
(median-index-iter2 (cdr lst) (+ 1 times_carred)))))
(median-index-iter2 lst 0))
的[获得从列表中方案的中间元件]可能的复制(http://stackoverflow.com/问题/ 13306626 /获取中间人元素 - 从列表式的方案)。 –