Solving Problems Using Recursion (Python):
To solve the problem, you have to use recursion and cannot use for or while loops to solve the problems as well as not using global variables.
3. Create a function that takes to strings and removes the similar letters from the longer one once.
Ex.
Input = "at" "radiator"
Output = "rdiaor"
notice how only the leftmost a was removed by the function
def remove_string(a, b): #functin definition
if len(a) == 0: #termination condition when length of shorter one becomes zero
return b #retruning string after removing shorter one
else:
if a[0] in b: #if letter is present in longer string
b = b.replace(a[0], '', 1)
return remove_string(a[1:], b) #recursive call
else: #if letter is not present in the string
return remove_string(a[1:], b) #recursive call
str1, str2 = input('Enter the two strings(space separated): ').split() #taking user input
if len(str1) > len(str2): #checking for longer among two
print(remove_string(str2, str1)) #calling the function
else:
print(remove_string(str1, str2))
Screenshot of output:
Get Answers For Free
Most questions answered within 1 hours.