Minimum element in a tree

时间:2016-02-12 22:02:53

标签: tree lisp common-lisp minimum

I want to find the minimum element (at any level) in a non-linear list (edit: a tree), in Lisp. I wrote something like:

rootobj.get("").getAsJsonArray();

But, it's not working (because of that condition for non-numerical atoms, I guess...). Does anyone have, any idea how to fix this code? Thanks in advance.

3 个答案:

答案 0 :(得分:2)

您的numberp案例永远不会执行,因为atom案例首先被测试,而数字是原子。所以每个数字都被99999取代。先放numberp个案例。

您的代码的另一个问题是,如果树中的最小数字大于99999,它将找不到最小的数字。要修复它而不更改代码太多,您需要自己的版本{{1 }}支持无限的表示:

min

然后,将(defun inf-min (a b) (cond ((eq a :infinity) b) ((eq b :infinity) a) ((< a b) a) (t b))) 替换为min,将99999替换为inf-min

答案 1 :(得分:2)

使用99999实际上是一种黑客攻击(不是好的黑客攻击),请不要这样做。使用:infinity稍微好一些,但是,在提供空列表时,您是否希望结果为:infinityloop方法更好,但是当列表为空时,最小化返回0,这通常不是我们想要的。

对于零值,最小函数未定义,因此我将定义tree-min函数,其中当树不包含数字时,nil中的结果为(defun tree-min (tree) (typecase tree ;; base case with numbers (number tree) ;; string are sequences too, but don't iterate over them. (string nil) ;; vectors and lists (sequence (reduce (lambda (m e) (let ((em (tree-min e))) (or (and m em (min em m)) ; Eminem? em))) tree :initial-value nil)))) 。像这样:

(tree-min #(3 2 nil (2 1 -20) 100 20 ))
=> -20

(tree-min nil)
=> nil

(tree-min '(a 20))
=> 20

该函数以静默方式跳过任何非数字元素。以下是一些例子:

Individ <- data.frame(Participant = c("Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "Jane", "Jane", "Jane", "Jane", 
                                      "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Bill", "Bill", "Bill", "Bill", "Bill", "Bill"),  
                      Time = c(1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6),
                      Condition = c("Placebo", "Placebo", "Placebo", "Placebo", "Placebo", "Placebo", "Expr", "Expr", "Expr", "Expr", "Expr", "Expr", 
                                    "Placebo", "Placebo", "Placebo", "Placebo", "Placebo", "Placebo", "Expr", "Expr", "Expr", "Expr", "Expr", "Expr"),
                      Location = c("Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", 
                                   "Away", "Away", "Away", "Away", "Away", "Away"),
                      Power = c(400, 250, 180, 500, 300, 450, 600, 512, 300, 500, 450, 200, 402, 210, 130, 520, 310, 451, 608, 582, 390, 570, 456, 205))

在实践中,您可以概括此函数以采用extremum之类的比较函数。

答案 2 :(得分:1)

(defun minimum (tree)
    (loop for item in tree
         if (consp item) minimize (minimum item)
         else if (numberp item) minimize item))
相关问题