Calculate String Length
In this lesson, you will learn how to calculate the length of a string using both an iterative and recursive approach in Python.
We'll cover the following...
In this lesson, we focus on the following problem:
Given a string, calculate its length.
If you are preparing for an interview or trying to understand the notion of recursion to solve a problem, I hope this lesson is helpful to you.
Python has a built-in len()
function which returns the length of a string. This is the standard way to obtain the length of a string in Python.
Press + to interact
input_str = "LucidProgramming"print(len(input_str))
Iterative Approach
Now we are going to code the same functionality ourselves in Python. Let’s begin with the iterative approach.
Press + to interact
# Iterative length calculation: O(n)def iterative_str_len(input_str):input_str_len = 0for i in range(len(input_str)):input_str_len += 1return input_str_len
On line 3, input_str_len
is initialized to 0
...