如何写在计划/ Lisp的这种数据结构的平均功能?
-
16-09-2019 - |
题
我想找到一个新的项目的基础上同类产品的平均价格的价格。
功能得到-K-类似用途的K-最近邻居,返回我这个输出
((list rating age price) proximity)
。
For example, 2-similar would be:
(((5.557799748150248 3 117.94262493533647) . 3.6956648993026904)
((3.0921378389849963 7 75.61492560596851) . 5.117886776721699))
我需要找到类似项目的平均价格。的117和75即平均。 有没有更好的办法来循环?我的功能看起来太丑陋。
(define (get-prices new-item)
(define (average-prices a-list)
(/ (cdr
(foldl (λ(x y) (cons (list 0 0 0)
(+ (third (car x)) (third (car y)))))
(cons (list 0 0 0) 0)
a-list))
(length a-list)))
(let ((similar-items (get-k-similar new-item)))
(average-prices similar-items)))
解决方案
您可以做简单的事,只是拉出每三个值:
(define (average-prices a-list)
(/ (apply + (map fourth a-list)) (length a-list)))
这是有点低效率的,因为它建立一个中间表,我的猜测是,这就是为什么你试过foldl
。下面是做到这一点的正确方法:
(define (average-prices a-list)
(/ (foldl (lambda (x acc) (+ (third x) acc)) 0 l)
(length a-list)))
有尚未成年的低效率 - length
正在做第二次扫描 - 但在这个时候,你不应该理会,因为你需要一些的真正的长列表以获得任何明显的放缓
其他提示
Common Lisp的
(/ (reduce '+ a-list :key 'caddar) (length a-list))
或
(loop for ((nil nil e) . nil) in a-list
count e into length
sum e into sum
finally (return (/ sum length)))
不隶属于 StackOverflow