I am trying to solve a problem using Python. The problem: Given a string like 'a b c d', replace the space with '_' for all combinations. So here, the expected output would be: 'a_b c d', 'a_b_c d', 'a_b_c_d', 'a b_c d', 'a b_c_d', 'a b c_d'
I am using a sliding window approach for this, here's my code:
ip = 'a b c d'
org = ip
res = []
for i in range(len(ip)):
if ip[i] == ' ': i += 1
for j in range(i + 1, len(ip)):
if ip[j] == ' ':
ip = ip[:j] + '_' + ip[j+1:]
res.append(ip)
j += 1
i += 1
ip = org
The problem is, the 2nd for loop is looping twice and appending duplicate results.
Result: ['a_b c d', 'a_b_c d', 'a_b_c_d', 'a b_c d', 'a b_c_d', 'a b_c d', 'a b_c_d', 'a b c_d', 'a b c_d']
I am not able to figure why this is happening, would appreciate any help.
Thanks!