所以我在做coderbyte的挑戰,我有問題之一: ArrayAdditionI,這裏的問題的聲明:Python的陣列加入遞歸
「」」 使用Python語言,具備的功能ArrayAdditionI(ARR)採用存儲在arr 中的數字數組,並返回字符串true,如果可以將數組中的任意數字組合加起來等於數組中的最大數字,則返回字符串false。 例如:如果arr包含[4,6,23,10,1,3],則輸出應該返回true,因爲4 + 6 + 10 + 3 = 23。 數組將不會爲空,不會包含所有相同元素,並可能包含負數。 「」」
因爲我不能這樣做,我研究了一個解決方案,我發現這一點:
def countFor(arr, m, s0):
if len(arr) == 0:
return False
a0 = arr[0]
ar = arr[1:]
sw = s0 + a0
if sw == m:
return True
if countFor(ar, m, sw):
return True
if countFor(ar, m, s0):
return True
return False
def ArrayAdditionI(arr):
m = max(arr)
arr.remove(m)
return str(countFor(arr, m, 0)).lower()
現在,我想確切地理解代碼的功能上的每個迴路是什麼,我打印出來的這個列表的每一個循環的輸出[4,6,23,10,1,3]:
Input: [4, 6, 10, 1, 3] 23 0
a0: 4
ar: [6, 10, 1, 3]
sw: 4
Input: [6, 10, 1, 3] 23 4
a0: 6
ar: [10, 1, 3]
sw: 10
Input: [10, 1, 3] 23 10
a0: 10
ar: [1, 3]
sw: 20
Input: [1, 3] 23 20
a0: 1
ar: [3]
sw: 21
Input: [3] 23 21
a0: 3
ar: []
sw: 24
Input: [] 23 24
Input: [] 23 21
Input: [3] 23 20
a0: 3
ar: []
sw: 23
True
,我跟隨並瞭解發生了什麼事情,直到最後三個環路,我不代碼的哪一部分使它從「輸入:[] 23 24」到「輸入:[] 23 21」到「輸入:[3] 23 20」。