2

I found a question in glassdoor. I do not have additional clarification

Input : an int array [1,0,0,1,1,0,0,1,0,1,0,0,0,1] you have to come up with a program that will give all possible subsets of the array based on the pattern. Pattern restrictions were the string array should start with 1 and end with 1. So there will be many sub arrays like from index 0 to 3 and 0 to 4 and index 7 to 9

To solve this I was thinking of using 2 for loops and if both cases the values are equal to 1 then print them.

v=[1,0,0,1,1,0,0,1,0,1,0,0,0,1]

resultList=[]

for i in range(0,len(v)-1):
    for j in range(i+1, len(v)):
        if v[i]==1 and v[j]==1:
            r=v[i:j]
            resultList.append(r)

print(resultList)

Output:[[1, 0, 0], [1, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 1, 0, 0, 1, 0], [1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0], [1], [1, 1, 0, 0],

I only see 1 correct value so far in output [1, 0, 0, 1]. Should I have used set instead of list? I tried that but that approach did not work either. Can someone kindly give some directions on how to solve this problem?

Thanks for your time.

Sheikh Rahman
  • 895
  • 3
  • 14
  • 29

2 Answers2

1

You can use itertools.combinations to pick 2 indices where the values are non-zeroes in the list:

from itertools import combinations
a = [1,0,0,1,1,0,0,1,0,1,0,0,0,1]
[a[i: j + 1] for i, j in combinations((i for i, n in enumerate(a) if n), 2)]

This returns:

[[1, 0, 0, 1], [1, 0, 0, 1, 1], [1, 0, 0, 1, 1, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 1, 0, 1], [1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1], [1, 1], [1, 1, 0, 0, 1], [1, 1, 0, 0, 1, 0, 1], [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1, 0, 1], [1, 0, 0, 1, 0, 1, 0, 0, 0, 1], [1, 0, 1], [1, 0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 1]]
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

The probelm is in v[i:j]. Change v[i:j] to v[i:j+1]

Shehan Ishanka
  • 593
  • 4
  • 5