The requirement is to find and remove the adjacent characters in a string if they are only A and B or C and D. I implemented the code but the return statement in line 5 is not returning the final string. If you pass input = 'CBACD', ideally it should give me output as C. whereas the below code is returning None. If I give input = 'C', in this case it is returning 'C'. I am unable to understand where the issue is. Can you help me find the bug here?
Note: It may not be a good performing code. But I only want to understand why the function is unable to return the value.
def solution(s):
print("Received", s)
if len(s) == 1:
print("Length is 1")
return s
else:
char_list = list(s)
break_flag = False
for i in range(0,len(char_list)):
if i >= len(char_list)-1:
pass
else:
if ord(char_list[i])-ord(char_list[i+1]) == -1 or ord(char_list[i])-ord(char_list[i+1]) == 1:
if ((char_list[i] == 'A' and char_list[i+1] == 'B') or \
(char_list[i] == 'B' and char_list[i+1] == 'A')) or \
((char_list[i] == 'C' and char_list[i + 1] == 'D') or \
(char_list[i] == 'D' and char_list[i + 1] == 'C')):
char_list.remove(char_list[i])
char_list.remove(char_list[i])
break_flag = True
print("BreakFalg is", break_flag)
print("New String is ", ''.join(char_list))
if break_flag:
print("Passing new string", ''.join(char_list))
solution(''.join(char_list))
else:
return ''.join(char_list)
input = 'CBACD'
print(solution(input))
I have a written another concise code. Even here I have the same issue. Replace if I find 'A' and 'B' adjacent to each other (like 'AB' or 'BA') or replace if 'C' and 'D' are adjacent (like 'CD' and 'DC'). This also gives me the same problem.
def solution(s):
print("Received:", s)
if len(s) == 1:
return s
else:
if 'AB' in s or 'BA' in s:
s = s.replace('AB','').replace('BA','')
solution(s)
elif 'CD' in s or 'DC' in s:
s = s.replace('CD', '').replace('DC', '')
solution(s)
else:
return s
Another verison:
def solution(s):
print("Received:", s)
if len(s) == 1:
return s
elif 'AB' in s or 'BA' in s:
s = s.replace('AB','').replace('BA','')
solution(s)
elif 'CD' in s or 'DC' in s:
s = s.replace('CD', '').replace('DC', '')
solution(s)
else:
return s
input = "CBACD"
print(solution(input))
All of them are returning None. Please help me identify where I am going wrong.