def num_not_increasing(L)"""
number of pairs in L that are not in increasing order.
switches([6, 1, 4]) returns 2, since (6, 1) and (6, 4) are out of order.
"""
我可以使用两个while循环和索引来轻松完成此操作,但是如何在python中递归地实现此目的呢?
编辑:我用while循环实现了什么:
def switches(L):
if len(L) < 2:
return 0
else:
i = 0
j = 1
count = 0
while i < len(L)-1:
while j <len(L):
if L[i] > L[j]:
count+=1
j+=1
i+=1
return count
答案 0 :(得分:1)
你期待这个吗?
def COUNT(ind, prev, L):
if(ind>=len(L)):
return 0
val = 0
val += COUNT(ind+1, prev, L)
if(L[ind]<=L[prev]):
val = val+1
return val
def num_not_increasing(lst):
val = 0
for i in range(len(lst)):
val += COUNT(i+1, i, lst)
return val
L = [6,1,5,4,2]
print num_not_increasing(L)