lisp - 根据条件从循环返回
问题描述
我有以下功能:
(defun chooseBest (TSPs dTSPs)
(let ((minim (minPos dTSPs 0 0)) (j 0) (best nil))
(loop for i in TSPs
do (cond ((= j minim) (progn (setf best i) (setq j (+ j 1))))
(t (setq j (+ j 1)))))
best))
该函数接收两个列表:
TSP - 类似这样的路径列表:
(((1 3600 2300) (2 3100 3300))
((3 4700 5750) (22 6650 2300) (23 5400 1600)))
以及与这些相关的距离列表:
(distancePath1 distancePath2)
该函数minPos
返回具有较小数字的列表的位置,即距离较小的路径。
鉴于此,该chooseBest
函数将返回较小的路径。
但我想改进它,因为它会在整个列表中搜索小数字,这是一种浪费,因为它minim
有那个位置。例如minim
是 2,但它正在评估一个有 100 条路径的 TSP 列表,我想在 2 上立即返回并打破循环,但返回不起作用......
解决方案
让我们稍微修改一下你的功能。
首先,具有更好的缩进:
(defun chooseBest (TSPs dTSPs)
(let ((minim (minPos dTSPs 0 0))
(j 0)
(best nil))
(loop for i in TSPs
do (cond ((= j minim)
(progn (setf best i)
(setq j (+ j 1))))
(t
(setq j (+ j 1)))))
best))
不需要progn
内部cond
:
do (cond ((= j minim)
(setf best i)
(setq j (+ j 1)))
(t
(setq j (+ j 1)))))
递增 j可以通过incf
:
(setq j (+ j 1)))
=>
(incf j)
您可以将let 变量移动到循环中。
(let ((minim (minPos dTSPs 0 0))
(j 0)
(best nil))
(loop for i in TSPs
=>
(loop for it in TSPs
for j from 0
with minim = (minPos dTSPs 0 0)
with best
do …)
for j from 0
启动一个计数器,with … =
声明一个在开始时计算的变量(而不是在每次迭代时)。
返回和条件
在循环中,我们可以多次使用if…do
, else…do
, when
and , and 。return
要在循环结束时执行某些操作,请使用finally
.
(defun chooseBest (TSPs dTSPs)
(loop for i in TSPs
for j from 0
with minim = (minPos dTSPs 0 0)
with best
if (= j minim)
do (progn (setf best i)
(incf j))
else
do (incf j)
finally (return best)))
搜索列表和序列的功能
现在,如果您想在列表中查找元素,您可以使用很多函数:find、nth、search、position,……参见https://lispcookbook.github.io/cl-cookbook/data-structures.html#函数因为minPos
返回一个索引,你可能想要nth index list
or elt sequence index
。
推荐阅读
- python - Numpy 函数参数混淆列表或元组
- python - 使用 pymysql 从 mysql 获取数据但返回 nan
- python - 如何迭代 json 输出并在数据框中获得理想的结果?
- java - 无法在 powermock 中使用 @PowerMockIgnore 创建restTemplate
- python-3.x - 错误:根:“进程”对象没有属性“get_open_files”
- r - 如何找到我的混淆矩阵的准确性?
- python - Python将32位二进制浮点数写入文件
- python - Pydantic上的递归orm模式?
- algorithm - O(n sqrt(n)) 算法是如何工作的,它列出了给定一个数字数组的所有可能的总和?
- wcf - 配置失败请求跟踪规则的异常