找出Lisp中算术级数的差异(Finding the difference in an arithmetic progression in Lisp)

编程入门 行业动态 更新时间:2024-10-11 01:10:00
找出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 diff

Current 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) ) )

更多推荐

本文发布于:2023-07-14 19:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1106722.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算术级数   差异   Lisp   Finding   progression

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!