4

我想根据类似商品的平均价格找到新商品的价格。函数 get-k-similar 使用 k-Nearest Neighbors 但返回给我这个输出 ((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)))
4

2 回答 2

5

通用 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)))
于 2009-07-17T18:05:07.943 回答
3

你可以做一个简单的事情,只需提取每三个值:

(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正在进行第二次扫描 - 但这是您不应该打扰的事情,因为您需要一些非常长的列表才能获得任何明显的减速。

于 2009-07-17T18:34:34.220 回答