在Applescript中,我需要找到最接近零但不是零的整数值。数字全为零或大于零。目前,我有三个整数。
我想我可以写一个循环,但是有更简单的方法吗?
示例:
{0,3,4} find 3.
{1,0,0} find 1
{4,10,2} find 2
{0,0,0} find nothing or 0
答案 0 :(得分:1)
您需要编写一个循环,因为在某个时候,列表中的每个项目都需要进行评估,因此就无法解决这个问题(假设使用迭代方法;您当然可以编写一个不包含以下内容的递归算法: t包含一个显式循环-我将在下面进行说明)。
迭代方法跟踪列表中的每个数字,以逐一的方式跟踪遇到的最低非零数字。当我们到达列表的末尾时,跟踪的值将是我们追求的结果:
on minimumPositiveNumber from L
local L
if L = {} then return null
set |ξ| to 0
repeat with x in L
set x to x's contents
if (x < |ξ| and x ≠ 0) ¬
or |ξ| = 0 then ¬
set |ξ| to x
end repeat
|ξ|
end minimumPositiveNumber
get the minimumPositiveNumber from {10, 2, 0, 2, 4} --> 2
递归方法将列表中的第一项与列表其余部分中的最低非零值进行比较,并保持最低非零值:
on minimumPositiveNumber from L
local L
if L = {} then return 0
set x to the first item of L
set y to minimumPositiveNumber from the rest of L
if (y < x and y ≠ 0) or x = 0 then return y
x
end minimumPositiveNumber
get the minimumPositiveNumber from {10, 2, 0, 2, 4} --> 2