General Question

zarnold's avatar

How to calculate median of a list of numbers in Scheme (Lisp)?

Asked by zarnold (708points) October 11th, 2007
Observing members: 0 Composing members: 0

6 Answers

Perchik's avatar

I don’t know Scheme at all.

Logically I’d say;
Sort the list.
If the number of items is odd, the median will be in the middle position. (middle position for an odd number would be ((NumInList – 1 ) / 2 ) + 1
for an even number the median is the two middle positions averaged together.

Something like :

sort list.
if (numInList odd) >> median =( ( numInList -1 ) / 2 ) + 1
else ( numList even) >> median = ( list[ numlist/2 -1 ] + list[numlist/2] ) / 2

where list[n] lets you access the nth position in the list and numList is the number in the list. (note the positions for the even number list may vary depending on whether your list starts at position 0 or 1)

Don’t know how to translate this into Scheme, but I hope this helped!

zarnold's avatar

thanks alot Perchik…I don’t think translating it should be too hard. I’ll just play around with Drscheme until it works :)

Perchik's avatar

Heh I just noticed that I used “numInList” and “numList” those both should be the same thing and it should be the number of items in the list.

FusionGyro's avatar

Forgive the poor markup. This is a Lisp solution (I think, it’s been a while since I’ve dealt with the median function).

(defun median (list)
(let ((sorted (sort list #’<))
(i (round (/ (length list) 2))))
(nth i sorted)))

I couldn’t figure out how to sort a list in DrScheme but I’m sure it’ll be an easy port.

sash's avatar

how to calculate the length of a list in scheme ?

sash's avatar

how to use cons,car,cdr in scheme give it with example

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther