Alexis
Alexis

Reputation: 2304

Quantity of subarrays in a pythonic way

I have this array:

[1,2,3,4]

and I want all the sub arrays you can get except by the single element, in this case:

 [1,2],[1,2,3],[1,2,3,4],[2,3],[2,3,4],[3,4]. 

So I have implemented this code:

def nSub(nums:list):
    """
    type nums: list
    """
    l_nums = len(nums)
    p = 2
    for i in range(l_nums):
        for j in range(p,l_nums+1): 
            print(nums[i:j])
        p += 1

nSub([1,2,3,4])

But although it works, perhaps there is other way to implement this, so I have this question: is there a pythonic way to do this? Any help will be greatly appreciated.

Upvotes: 0

Views: 72

Answers (1)

mcsoini
mcsoini

Reputation: 6642

Simple list comprehension should do the job:

arr = [1,2,3,4]

[arr[n1:n2] 
 for n1 in range(0, len(arr) + 1)
 for n2 in range(n1 + 2, len(arr) + 1)]

Output:

[[1, 2], [1, 2, 3], [1, 2, 3, 4], [2, 3], [2, 3, 4], [3, 4]]

Upvotes: 1

Related Questions