Home > front end >  Write a recursive function
Write a recursive function

Time:02-28

I am trying to write a function to compare the letters in 2 strings.

If the 2 letters are in same position then replace it with '!' and '^' if otherwise.

S1: 'ABACADABRA'

S2: 'ACABADACCD'

This is my code using iterative method: enter image description here

def Compare_String_I(S1,S2):
difference = ''
if len(S1) == len(S2):
    for i in range(0, len(S1)) and range(0,len(S2)):
        if S1[i] != S2[i]:
            difference  = str('^')
        else:
            difference  = str('!')
    return difference

I am trying to learn how to write the code recursively, but I am not sure how to do it.

CodePudding user response:

How about this:

def compare_string(S1, S2):
    if len(S1) != len(S2):
        return
    
    diff = ''
    for s1, s2 in zip(S1, S2):
        diff  = '!' if s1 == s2 else '^'
    return diff

print(compare_string('aaa', 'aba'))  # !^!

CodePudding user response:

if len(s1) != len(s2):
    quit()
else:
    i = 0 
    while i < len(s1):
        if s1[i] == s2[i]:
            s1 = s1.replace(s1[i], "!")
            s2 = s2.replace(s2[i], "^")
        i  = 1

print(f"{s1}\n{s2}")
  • Related