我正在試圖製作一個名爲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 /獲取中間人元素 - 從列表式的方案)。 –