找出Lisp中算术级数的差异(Finding the difference in an arithmetic progression in Lisp)
我对Lisp 完全陌生。
如何找到算术级数系列中元素之间的差异?
例如
(counted-by-N '(20 10 0))返回-10
(counted-by-N '(20 10 5)) (counted-by-N '(2)) (counted-by-N '())返回Nil
在Python / C和其他语言中,它非常简单......有点被困在Lisp中。
我的伪算法是这样的:
function counted-by-N(L): if len(L) <= 1: return Nil else: diff = L[second] - L[first] for (i = second; i < len(L) - 1; i++): if L[i+1] - L[i] != diff return Nil return diff目前的工作:
(defun count-by-N (L) (if (<= (length L) 1) Nil ( (defvar diff (- (second L) (first L))) ; How to do the loop part? )) )I am totally new to Lisp.
How to find the difference between elements in an arithmetic progression series?
e.g.
(counted-by-N '(20 10 0))Return -10
(counted-by-N '(20 10 5)) (counted-by-N '(2)) (counted-by-N '())Returns Nil
In Python/C and other languages, it is very straightforward... Kinda stuck here in Lisp.
My pseudo algorithm would be something like this:
function counted-by-N(L): if len(L) <= 1: return Nil else: diff = L[second] - L[first] for (i = second; i < len(L) - 1; i++): if L[i+1] - L[i] != diff return Nil return diffCurrent work:
(defun count-by-N (L) (if (<= (length L) 1) Nil ( (defvar diff (- (second L) (first L))) ; How to do the loop part? )) )最满意答案
(flet ((by-n (list &aux (e1 (first list)) (e2 (second list)) (difference (and e1 e2 (- e2 e1)))) (and difference (loop for (one two) on list while (and one two) when (/= (- two one) difference) do (return-from by-n nil))) difference)) (by-n '(20 10 0)))要么
(flet ((by-n (list &aux (e1 (first list)) (e2 (second list)) (difference (and e1 e2 (- e2 e1)))) (when difference (loop for (one two) on list while (and one two) when (/= (- two one) difference) do (return-from by-n nil)) difference))) (by-n '(20 10 0)))Here is my final answer of this question which uses recursion:
(defun diff (N) (- (second N) (first N)) ) (defun count-by-N (L) (cond ((null L) nil) ((= (length L) 1) nil) ((= (length L) 2) (diff L)) ((= (diff L) (diff (rest L))) (count-by-N (rest L))) (T nil) ) )更多推荐
发布评论