I am new to python and this is my interview question. How to Replace a substring from main string without using replace function or any other inbuilt functions
Examples : appleandapple Output: bananaandbanana
I am new to python and this is my interview question. How to Replace a substring from main string without using replace function or any other inbuilt functions
Examples : appleandapple Output: bananaandbanana
I think, since this is an interview question, you should invest a lot more effort in this than just posting the question here. But I am not here to tell you how to handle your interview preparations.
What you can do is treat the string as a character array and cut out slices the size of your key which is to be replaced. The following solution may not be the fastest possible but since your are not allowed to use replace(), performance may not be the priority here. So without using any string-based built-Ins, my first guess would be something as the following:
def replace_custom(target: str, to_be_replaced: str, replace_with: str) -> str:
for i in range(len(target)-len(to_be_replaced)+1):
if target[i:len(to_be_replaced) + i] == to_be_replaced:
new_target = '{}{}{}'.format(target[:i], replace_with, target[len(to_be_replaced) + i:])
return replace_custom(new_target, to_be_replaced, replace_with)
return target
And calling it like this:
a = 'appleandapple'
b = 'apple'
c = 'banana'
print(replace_custom(a, b, c))
'{}{}{}'.format(…) is a string builtin method.Look ma, no builtins, no methods
In [35]: def sub(s, a, b):
...: def l(s):
...: l=0
...: for _ in s: l+=1
...: return l
...: ls, la = l(s), l(a)
...: i, out = 0, ""
...: while i<ls:
...: if s[i:i+la] == a :
...: out += b
...: i = i+la
...: else:
...: out += s[i]
...: i = i+1
...: return out
...: sub('appleandapple', 'apple', 'banana')
Out[35]: 'bananaandbanana'
If I was asked this question, I would have solved it this way using String slicing.
I don't think any interviewer will put restrictions on using
len()andrange()as they are very trivial in Python.
s = 'appleandapple'
sub_s = 'apple'
rep_s = 'banana'
ans = ''
# Stores the {start_idx: end_idx} of matched substring
indices = {}
for i in range(0, len(s)-len(sub_s)+1):
if s[i:i+len(sub_s)] == sub_s:
indices[i] = i+len(sub_s)-1
i = 0
while i < len(s):
if i in indices:
ans += rep_s
i += indices[i]
else:
ans += s[i]
i += 1
print(ans)
# Output:
bananaandbanana