Python Basics

Program to calculate length of string using recursion

Detailed guide and Python implementation for the 'Program to calculate length of string using recursion' problem.

問題提起

Write a function string_length(s) that calculates and returns the length of the string s using recursion. You must NOT use the built-in len() function. The base case is an empty string which has length 0. For each recursive call, count one character and recurse on the remaining string.

制約
  • 0 <= len(s) <= 1000
  • s contains only printable ASCII characters

Example 1
Input
s = 'hello'
Output
5
Explanation

The string 'hello' has 5 characters: h, e, l, l, o.

Example 2
Input
s = 'python'
Output
6
Explanation

The string 'python' has 6 characters.

Example 3
Input
s = ''
Output
0
Explanation

An empty string has length 0.

Need a Hint?
Consider using Recursion-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。