我编写了一个名为 my_rotate
的函数,它从用户那里获取一个数字并创建一个最多五个数字的列表。 my_rotate
然后,弹出列表的第一个元素并将其添加到列表的末尾。关于如何编写 my_rotate
以接收另一个数字 n
并根据用户输入的数字 n
旋转列表的任何建议.
示例:
> (my_rotate 1 2)
输出:
(3 4 5 1 2)
这是我目前所拥有的:
(defun my_rotate (y)
(append (loop for i from (+ 1 y) to (+ 4 y) collect i)
(list y)))
最佳答案
这里是函数。 我创建了两个列表,然后将它们连接起来。
(defun my-rotate (length shift)
"Return a list of given LENGTH, rotated by SHIFT."
(nconc
(loop for i from (1+ shift) to (- length shift -2) collect i)
(loop for i from 1 to shift collect i)))
(my-rotate 7 2)
==> (3 4 5 6 7 1 2)
请注意,由于 loop
产品fresh列表,我使用 nconc
而不是 append
.
但是,如果您想轮换现有列表,则需要执行其他操作:
(defun rotate-list (list shift)
"Rotate the given LIST by the specified SHIFT."
(let ((len (length list)))
(setq shift (mod shift len)) ; handle circular shifts
(append (nthcdr (- len shift) list)
(butlast list shift))))
(rotate-list '(1 2 3 4 5 6) 2)
==> (5 6 1 2 3 4)
(rotate-list '(1 2 3 4 5 6) 20)
==> (5 6 1 2 3 4) ; same because 20 = 2 mod 6
(rotate-list '(1 2 3 4 5 6) 0)
==> (1 2 3 4 5 6) ; unchanged
请注意 nthcdr
指向原始列表中,因此我们必须使用 append
来避免修改参数。
另请注意,我们扫描list
参数两次(一次在nthcdr
中,一次在butlast
中)。
如果你的列表很大,并且分析显示这个函数是瓶颈,你可能想使用循环重写它(这种情况不太可能发生,我已经后悔浪费我的时间写这篇笔记了)。
关于list - 有关如何处理此 lisp 函数的建议。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42334010/