如果輸入數組分別是算術和幾何系列,則下面的代碼返回「算術」,「幾何」,如果兩者都不是,則返回-1。算術/幾何系列
雖然代碼工作正常,當我改變
if s = arr.length - 1
到
if s == arr.length - 1
在while
循環中,代碼不能正常工作了。
我不明白爲什麼。不應該==
而不是=
?
def ArithGeo(arr)
# code goes here
len = arr.length
difference = arr[len-1] - arr[len-2]
ratio = arr[len-1]/arr[len-2]
k = 0
s = k + 1
while (arr[s] - arr[k]) == difference && s < arr.length
if s = arr.length - 1
return "Arithmetic"
end
k += 1
end
k = 0
while arr[s]/arr[k] == ratio && s < arr.length
if s = arr.length - 1
return "Geometric"
end
k += 1
end
return -1
end
謝謝您解釋其背後的基本原理。 – IliasP