列出所有连续的子数组 [英] List all contiguous sub-arrays
本文介绍了列出所有连续的子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个整数数组[1, 2, 3]
,我需要返回该数组的连续子数组的所有可能组合.
I have an array [1, 2, 3]
of integer and I need to return all the possible combination of contiguous sub-arrays of this array.
[[1],[2],[3],[1,2],[2,3],[1,2,3]]
如何使用python处理呢?一种方法是具有2个循环和数组本身,但应该有一种更好的方法.
How can I handle that with python? One way would be to have 2 loops and the array itself but there should be a better way.
推荐答案
简化检查员的解决方案:
Simplifying the Inspector's solution:
def getAllWindows(L):
for w in range(1, len(L)+1):
for i in range(len(L)-w+1):
yield L[i:i+w]
还有一个完全没有循环的解决方案:
And a solution using no loops at all:
def allSubArrays(L,L2=None):
if L2==None:
L2 = L[:-1]
if L==[]:
if L2==[]:
return []
return allSubArrays(L2,L2[:-1])
return [L]+allSubArrays(L[1:],L2)
这篇关于列出所有连续的子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文