-1

I was writing a Python program to generate all possible substrings of a given input string using itertools.

def substring_generator(seq):
    substring_list = list(seq)
    return chain.from_iterable(combinations(substring_list, r) for r in range(len(seq) + 1)) 
print list(map(''.join, substring_generator('LLRR')))

to output ['', 'L', 'L', 'R', 'R', 'LL', 'LR', 'LR', 'LR', 'LR', 'RR', 'LLR', 'LLR', 'LRR', 'LRR', 'LLRR']. But I was wondering how I could also output the indices for each character in the substring e.g. seq = L0L1R2R3 a substring would be L0R2 or L1R2R3 Is there any way I could do this without having to edit too much of the existing code?

user68472
  • 1
  • 1
  • Where did "R1" come from? – Ignacio Vazquez-Abrams Jul 29 '17 at 21:13
  • I function doesn't return the correct result. the string `'L0R2R3'` is not a substring of `'L0L1R2R3'`. It is a __subset__ thought of the `seq`. The correct substring list of `'LLRR'` is `['', 'L', 'L', 'R', 'R', 'LL', 'LR', 'RR', 'LLR', 'LRR', 'LLRR']` – bergerg Jul 29 '17 at 21:29

2 Answers2

0

Since you already have the function, I would simply change the input passed to it:

substring_generator([c+str(i) for i, c in enumerate('LLRR')])

Complete code:

def substring_generator(seq):
    substring_list = list(seq)
    return chain.from_iterable(combinations(substring_list, r) for r in range(len(seq) + 1)) 
print list(map(''.join, substring_generator([c+str(i) for i, c in enumerate('LLRR')])))
# output: ['', 'L0', 'L1', 'R2', 'R3', 'L0L1', 'L0R2', 'L0R3', 'L1R2', 'L1R3', 'R2R3', 'L0L1R2', 'L0L1R3', 'L0R2R3', 'L1R2R3', 'L0L1R2R3']
EsotericVoid
  • 2,306
  • 2
  • 16
  • 25
0

i think what you want can be handled as follows:

def substring_generator(seq):
    substring_list = list(seq)
    return chain.from_iterable(combinations(substring_list, r) for r in range(len(seq) + 1)) 
print  list(map(''.join, substring_generator('LLRR'))) 
print  list(map(''.join, substring_generator('0112'))) 

gives:

['', 'L', 'L', 'R', 'R', 'LL', 'LR', 'LR', 'LR', 'LR', 'RR', 'LLR', 'LLR', 'LRR', 'LRR', 'LLRR']
['', '0', '1', '1', '2', '01', '01', '02', '11', '12', '12', '011', '012', '012', '112', '0112']

just look at the columns vertically or do you want to merge the string?


Update to include merge:

a = list(map(''.join, substring_generator('LLRR'))) 
b = list(map(''.join, substring_generator('0112'))) 

def f1(s,v):
  t = ''
  for i in range( len(s)  ):
    t += s[i] + v[i]
  return t

print [f1(x,y) for x,y in zip(a,b)]

that gives the output:

['', 'L0', 'L1', 'R1', 'R2', 'L0L1', 'L0R1', 'L0R2', 'L1R1', 'L1R2', 'R1R2', 'L0L1R1', 'L0L1R2', 'L0R1R2', 'L1R1R2', 'L0L1R1R2']
paolov
  • 2,139
  • 1
  • 34
  • 43