Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print all subarrays of a given array

Given an array write an algorithm to print all the possible sub arrays. The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the array A. Then in the next lines are N space separated values representing the array A. Print each sub-array element on a new-line.

t = int(input())
for z in range(t):
    n = int(input()) 
    a = list(map(int, input().split()))  

    for i in range(n):
        for j in range(i,n+1):
            for k in range(i,j):
                print(a[k], end=" ")
            print()

Sample Input

1
3
1 2 3 

Sample Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1 
1 2 
1 2 3 
2 
2 3 
3

I’ve tried everything best I can do.

>Solution :

If your issue is that you have empty lines, simplify your code to directly slice the list will all needed items.

You can use unpacking in print to have space separated elements by default.

t = int(input())
for z in range(t):
    n = int(input()) 
    a = list(map(int, input().split()))  

    for i in range(n):
        for j in range(i+1,n+1):
            print(*a[i:j])

input/ouput:

1
3
1 2 3  # end of input
1
1 2
1 2 3
2
2 3
3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading