a function median in Scheme

筅森魡賤 提交于 2019-12-02 17:41:42

问题


I am new to Scheme and I am using Dr.Racket to try to find the median of the list.

If the length of list L is odd, the function median returns the median element in the list. If the length of L is even, the function median returns 0. example

(median ‘(1)) returns 1
(median ‘(1 2)) returns 0
(median ‘(1 2 3)) returns 2
(median ‘( 1 2 3 4) returns 0

i am only allowed to use

- null?
- car
- cdr
- else
- = 
- +
- median
- cond
- if
- user defined names (for my variables)
- integer literals
- parentheses

Any ideas?


回答1:


This problem can be solved using the tortoise and hare algorithm, provided that a helper inner procedure is allowed - we need to pass two parameters for this to work. Other than that, all the restrictions are enforced:

(define (median lst)
  (define (median tortoise hare)
    (cond ((null? hare) 0)
          ((null? (cdr hare)) (car tortoise))
          (else (median (cdr tortoise) (cdr (cdr hare))))))
  (median lst lst))

It works as expected:

(median '(1))       ; returns 1
(median '(1 2))     ; returns 0
(median '(1 2 3))   ; returns 2
(median '(1 2 3 4)) ; returns 0


来源:https://stackoverflow.com/questions/27139794/a-function-median-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!