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
1
1 2
1 2 3
2
2 3
3
I've tried everything best I can do.
CodePudding user response:
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
CodePudding user response:
(try this) You can get and print all subset of an array by the next:
# Python3 program to find all subsets
# by backtracking.
# In the array A at every step we have two
# choices for each element either we can
# ignore the element or we can include the
# element in our subset
def subsetsUtil(A, subset, index):
print(*subset)
for i in range(index, len(A)):
# include the A[i] in subset.
subset.append(A[i])
# move onto the next element.
subsetsUtil(A, subset, i 1)
# exclude the A[i] from subset and
# triggers backtracking.
subset.pop(-1)
return
# below function returns the subsets of vector A.
def subsets(A):
global res
subset = []
# keeps track of current element in vector A
index = 0
subsetsUtil(A, subset, index)
# Driver Code
# find the subsets of below vector.
array = [1, 2, 3]
# res will store all subsets.
# O(2 ^ (number of elements inside array))
# because at every step we have two choices
# either include or ignore.
subsets(array)
CodePudding user response:
Instead of what you have done, you can go through a simple and general way like this:
a = input().split()
for i in range(len(a)):
for j in range(len(a)):
if j>=i:
print(*a[i:j 1])
Output:
1
1 2
1 2 3
2
2 3
3
CodePudding user response:
Try the following:
t = int(input())
for z in range(t):
n = int(input())
a = []
for y in range(n):
x = int(input())
a.append(x)
for i in range(n):
for j in range(i,n 1):
for k in range(i,j):
print(a[k], end=" ")
print()
