Hi I have a question with regards to python programming for my assignment
The task is to replace the occurrence of a number in a given value in a recursive manner, and the final output must be in integer
i.e. digit_swap(521, 1, 3) --> 523 where 1 is swapped out for 3
Below is my code and it works well for s = 0 - 9 if the final answer is outputted as string
def digit_swap(n, d, s):
result = ""
if len(str(n)) == 1:
if str(n) == str(d):
return str(s)
else:
return str(n)
elif str(n)[0] == str(d):
result = result + str(s) + str(digit_swap(str(n)[1:], d, s))
return result
else:
result = result + str(n)[0] + str(digit_swap(str(n)[1:], d, s))
return result
However, I have trouble making the final output as Integer The code breaks down when s = 0 i.e. digit_swap(65132, 1, 0) --> 6532 instead of 65032
Is there any fix to my code?
def digit_swap(n, d, s):
result = ""
if len(str(n)) == 1:
if str(n) == str(d):
return str(s)
else:
return str(n)
elif str(n)[0] == str(d):
result = result + str(s) + str(digit_swap(str(n)[1:], d, s))
return int(result) # Changes
else:
result = result + str(n)[0] + str(digit_swap(str(n)[1:], d, s))
return int(result) # Changes