I set myself the task to calculate the average of a list, but with two conditions:
- negative numbers are ignored
- numbers greater than 100 are counted as if they were 100
So the "skewed" average of the list '(1 -3 42 297 14) should be (1 + 42 + 100 + 14) / 4 (157/4).
I wrote 2 functions that do that. Please review and comment.
(defun skewed-average1 (list)
"calculate average by summing and dividing"
(let ((sum 0) (n 0))
(dolist (x list)
(if (>= x 0)
(progn
(if (> x 100) (setf x 100))
(setf sum (+ x sum))
(setf n (+ 1 n)))))
(/ sum n)))
(defun skewed-average2 (list)
"calculate average by building 'fixed' list"
(let (newlist)
(dolist (x list)
(if (>= x 0)
(progn
(if (> x 100) (setf x 100))
(setf newlist (cons x newlist)))))
(/ (apply #'+ newlist) (length newlist))))
(let ((numbers '(1 -3 42 297 14)))
(print (skewed-average1 numbers))
(print (skewed-average2 numbers)))
Also, how should errors be treated? Imagine passing an empty list to the functions; or a list with all negative numbers.