我想找到最后一个数字原子(在任何级别)为奇数的任何级别的子列表的数量。 例如:
'(A (B 2) (1 C 4) (D 1(9 F)) ((G 7) 6))
答案应该是 3.(D 1 (9 F)),(9 F),(G 7)。
我的代码:
(DEFUN numara (l)
(COND
((atom l) 0)
((verif l) (+ 1 (apply '+ (mapcar #'numara l))))
(t (apply '+ (mapcar #'numara l)))
)
)
(DEFUN transform(l)
(COND
((null l) nil)
((numberp (car l)) (cons (car l) (transform (cdr l))))
((atom (car l)) (transform (cdr l)))
(t (append (transform (car l)) (transform (cdr l))))
)
)
(DEFUN verif (l)
(COND
((null (transform l)) nil)
((= 1(mod (reverse (transform l)) 2)) t)
(t nil)
)
)
问题出在 verif 函数中。如果我执行
numara '(A (B 2) (1 C 4) (D 1(9 F)) ((G 7) 6))
它给我一个错误,它说:
Cannot take car of 1.
如何解决?
最佳答案
一个更简单的解决问题的方法是这样的:
(defun last-numeric (list)
"Return the last numeric element of a list."
(find-if #'numberp list :from-end t))
(defun count-odd-last-numbers (list)
"Recursively count all lists where the last numeric element is odd."
(if (listp list)
(let ((l-num (last-numeric list)))
(+ (if (and l-num (oddp l-num))
1 0)
(loop for el in list
sum (count-odd-last-numbers el))))
0))
last-numeric
使用 find-if
查找列表中满足给定谓词 #'numberp
的最后一个元素。 count-odd-last-numbers
将检查参数是否为列表;如果不返回 0;如果是,检查 last-numeric
是否返回奇数,并循环遍历所有元素,递归地调用它们并对结果求和。
作为给您的一般建议,您不应该在 Lisp 代码的单独行上使用结束括号。此外,在发布代码供其他人查看时,您还应该尝试为您的函数和变量提供更具描述性的英语名称。在 Lisp 中,您还可以在函数体中首先包含一个字符串(请参阅我的函数);那是一个文档字符串,应该解释函数的目的。您可以使用 (describe #'last-numeric)
查看函数的文档字符串,或者使用您的开发环境查看它(例如 slime-describe-function
) .
关于lisp 每个子列表奇数的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34711400/