Skip to content
Advertisement

finding possible combination from a given number that starts and ends with common number within the string

**String looks like **

num_str = '0110101'

Possible number of combination is to be find where the number starts and ends with 1

for example

11
1101
101
10101
110101

Advertisement

Answer

The following works for one interpretation of your question. It works by first finding the indices of the ones, looping over all pairs of those indices, and then slicing:

import itertools

num_str = '0110101'
ones = (i for i,d in enumerate(num_str) if d == '1')
for i,j in itertools.combinations(ones,2):
    print(num_str[i:j+1])

Output:

11
1101
110101
101
10101
101

If all you want is the set of such numbers (without any duplicates) then the loop can add numbers to a set rather than print them.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement