Write a function add_spaces(s) that takes an arbitrary string s as input and uses recursion to form and return the string formed by adding a space between each pair of adjacent characters in the string. If the string has fewer than two characters, it should be returned without any changes. Here are three examples: >>> add_spaces('hello') result: 'h e l l o' >>> add_spaces('hangman') result: 'h a n g m a n' >>> add_spaces('x') result: 'x' This function is somewhat similar to the the replace function from lecture, because it needs to recursively create a new string from an existing string. However, your function will be simpler, because it won’t need to decide what to do after the recursive call returns.

Respuesta :

Answer:

The solution code is written in Python:

  1. def add_spaces(s):
  2.    if len(s) < 2:
  3.        return s  
  4.    else:
  5.        return s[0] + " " + add_spaces( s[1 : ] )

Explanation:

Recursive function is a function that will call itself within the same function.

Let create a function named add_spaces() that take one input string, s (Line 1).

Next, create an if condition to check if the length of the input string is less than 2 (this means if the string has only one character), return the current string (Line 2-3).

Otherwise, it should return the first character of string, s[0] concatenated with a single space " " and concatenated again with the return output from the recursive calling add_spaces() that take s[1: ] as input parameter (Line 4-5). Please note s[1: ] is an expression we get the substring of the current string from position 1 till the end of string.

Answer:

C++.

#include <iostream>

#include <string>

using namespace std;

///////////////////////////////////////////////////////////////////

string add_spaces(string input) {

   if (input.length() < 2)

       return input;

   else {

       string minus_input = input.substr(0, input.length()-1);

       return add_spaces(minus_input) + " " + input[input.length()-1];

   }

}

///////////////////////////////////////////////////////////////////

int main() {

   cout<<add_spaces("hangman");

   return 0;

}

///////////////////////////////////////////////////////////////////

Explanation:

A Recursive function calls itself inside its body. To prevent it from running forever, there's a break condition inside recursive functions.

In our example it was a single character string.

We use recursion to solve problems by breaking them into smaller pieces.

In our example, we broke down the original string from the last character, till it only has its starting character. When the last character was encountered, we returned as it is in the break condition.

From there onward, all characters were getting separated by a space, till we reach the first add_spaces function call, where we return the full string with space between them.