a function median in Scheme

后端 未结 1 1384
野性不改
野性不改 2021-01-26 04:07

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

相关标签:
1条回答
  • 2021-01-26 05:14

    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
    
    0 讨论(0)
提交回复
热议问题