Problem 2 Motivation In computer science, we often use induction to prove the correctness of a function - that is, we prove formally that the function does what it is supposed to do. This is sometimes called "proving a function." For example, consider the Python function below, which reverses an input string using recursion. def reverse_string(s): |||||| reverse the string s. The first letter becomes the last letter, the second letter becomes the second- args: s, the string to be reversed returns: the reversed string if s == ""; return "" else: return reverse_string(s [1:])+s[0] Here it is in action. reverse_string("CSCI 0200") ¹0020 ICSC' We got the right answer for this input! But...would we get the right answer on every possible input? Let's write a proof which will guarantee that we will.
Solve Problem 2 by using an induction.
At the base case, let us consider an empty string and a one letter character.
I.e., when n = 0,
Then s = " "
So, its reverse is " ", which is returned by the function as well by its definition.
Again, when n = 1,
Then s = some single character string, say "a".
Then, its reverse is also "a", which we can write as s[0] + " " = s[0] + reverse_string(" ")
= s[0] + reverse_string(s[1:])
Here, s[1:] = " ", as s is a single character string.
Hence, we see, the function reverses a string for n = 0, 1 successfully.
Let us assume, the function reverses a string of length k for some k > 0.
i.e., let, s = s1s2s3............sk-1sk
[ here each si is some character ]
Then, reverse_string(s) = sksk-1............s3s2s1
Step by step
Solved in 3 steps with 1 images