什么是最大的数组,从给定的数组以相反的顺序排序?
Input: [25,28,11,10,9, 8,17, 23,20,19,14]
Output:[[28,11,10,9,8],[23,20,19,14]]
我试过谷歌但没有找到任何解决方案请帮我解决这个问题。这是我想写的代码,但并不清楚。
def findRuns(L):
result = []
start = 0
n = L[start]
for i,num in enumerate(L):
if num <= n:
n = num
else:
answer.append(L[start:1])
start = i
n = L[i]
result.append(L[start])
return result
请帮我解决这个问题。在此先感谢。
答案 0 :(得分:1)
def findRuns(L):
answer = []
start = 0
n = L[start]
for i,num in enumerate(L[1:],1):
if num <= n:
n = num
else:
answer.append(L[start:i])
start = i
n = L[start]
answer.append(L[start:])
return answer
输出:
In [48]: findRuns([25,28,11,10,9, 8, 23] )
Out[48]: [[25], [28, 11, 10, 9, 8], [23]]
In [49]: findRuns([25,28,11,10,9, 8,17, 23,20,19,14] )
Out[49]: [[25], [28, 11, 10, 9, 8], [17], [23, 20, 19, 14]]
答案 1 :(得分:1)
您可以编写一个石斑鱼函数,然后使用max()
找到基于长度的最大组:
def grouper(seq):
it = iter(seq)
grp = [next(it)]
for item in it:
if item <= grp[-1]:
grp.append(item)
else:
yield grp
grp = [item]
if grp:
yield grp
inp1 = [25,28,11,10,9, 8, 23]
inp2 = [25,28,11,10,9, 8,17, 23,20,19,14]
print max(grouper(inp1), key=len)
#[28, 11, 10, 9, 8]
print max(grouper(inp2), key=len)
#[28, 11, 10, 9, 8]
print list(grouper(inp2))
#[[25], [28, 11, 10, 9, 8], [17], [23, 20, 19, 14]]