Python 列表中未按递增顺序排列的项目数
我可以很容易地使用两个while循环和索引,但是如何在python中递归地实现这一点呢 编辑:我通过while循环实现的:Python 列表中未按递增顺序排列的项目数,python,list,recursion,Python,List,Recursion,我可以很容易地使用两个while循环和索引,但是如何在python中递归地实现这一点呢 编辑:我通过while循环实现的: 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. """ def开关(L): 如果l
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.
"""
def开关(L):
如果len(L)<2:
返回0
其他:
i=0
j=1
计数=0
而i
您是否期望这样
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
def计数(ind、prev、L):
如果(ind>=len(L)):
返回0
val=0
val+=计数(ind+1,上一个,L)
如果(L[ind]为什么是递归的?这不是你最好的选择。递归的,因为我正在做一系列问题来复习考试中的递归问题解决方法,这是我一直坚持的问题之一。
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)