Write a function average-above-max
, which takes 2 lists, L1
and L2
. L1
and L2
are both simple lists, which do not contain nested l开发者_运维技巧ists. Both lists may have non-numeric elements.
The result of the function is the average of the numbers in L2
that are larger than the largest number in L1.
If there is no number in L1
, all the numbers in L2
should be used to calculate the average.
If there is no number in L2
, the average is 0
.
For example, the result of (average-above-median (list 2 'a 1) (list 'b 5 3 1))
should be 4
.
And this is what I have:
(define (filter l n)
(cond
((null? l) empty)
((number? (car l)) (cons (car l) (filter (cdr l))))
(else (filter (cdr l)))))
which only picks numbers out of a list.
Haven't seen CS101, but I hope I solved your problem:
(define (avg xs)
(/ (foldl + 0 xs) (length xs)))
(define (list-max xs)
(let loop ((xs xs)
(e (car xs)))
(if (empty? (cdr xs))
e
(loop (cdr xs) (max e (car xs))))))
(define (average-above-median xs ys)
(let* ((xsnum (filter number? xs))
(ysnum (filter number? ys)))
(if (empty? ysnum)
0
(if (empty? xsnum)
(avg ysnum)
(avg (filter (lambda(x) (> x (list-max xsnum))) ysnum))))))
Example:
> (average-above-median (list 2 'a 1) (list 'b 5 3 1))
4
> (average-above-median (list) (list 'b 5 3 1))
3
> (average-above-median (list 2 'a 1) (list))
0
> (average-above-median (list) (list))
0
Hope that helps.
精彩评论