<分区>
我正在做的任务是:
Given an array of ints, compute recursively the number of times that the value 11 appears in the array. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array.
我需要递归地执行此操作。我对此很陌生,但从技术上讲我做到了。 我有以下内容:
def array11(arr, index, cnt=0, num=0):
if(cnt==len(arr)-index):
print("yay!!! number 11 appears %d times"%num)
return
elif(arr[index:][cnt]==11):
num+=1
cnt+=1
array11(arr,index,cnt,num)
else:
cnt+=1
array11(arr,index,cnt,num)
但我觉得出于某种原因我通过添加具有默认值的“cnt”和“num”参数来实现它是一种廉价的方式。我只是不知道如何在没有计数器的情况下遍历“arr”数组!!
所以这是可以接受的?你会这样做吗?
提前致谢