Section 5. Chapter 2
single
Challenge: Formatting a Phone Number
Swipe to show menu
Recall that a recursive function solves a problem by calling itself with a simpler input, until it reaches the base case that stops the recursion:
1234def list_sum(numbers): if not numbers: # Base case return 0 return numbers[0] + list_sum(numbers[1:]) # Recursive case
Notice how each recursive call works on a smaller version of the input — in this case, the list without its first element. The same approach applies when processing strings character by character.
Task
Swipe to start coding
Given a string representing a phone number, which may contain spaces, dashes, parentheses, or other non-numeric characters. The goal is to extract only the digits using recursion.
- If the input string
numberis empty, return an empty string; - Check if the first character of the string
numberis a digit using theisdigit()method; - If it is a digit, concatenate it with the result of a recursive call passing the substring starting from the second character;
- If it is not a digit, make a recursive call skipping the first character.
Solution
Everything was clear?
Thanks for your feedback!
Section 5. Chapter 2
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat