Write your own len() in Python
The method len() returns the number of elements in the list or length of the string depending upon the argument you are passing. How to implement without using len():
Approach:
- Take input and pass the string/list into a function which return its length.
- Initialize a count variable to 0, this count variable count character in the string.
- Run a loop till the length if the string and increment count by 1.
- When loop is completed, return count.
Below is the implementation of the above approach:
Python
# Function which return length of string def findLength(string): # Initialize count to zero count = 0 # Counting character in a string for i in string: count + = 1 # Returning count return count # Driver code string = "w3wiki" print (findLength(string)) |
13
Time Complexity: O(n)
Auxiliary Space: O(1)
Another Approach:
- Take input and pass the string/list into a function that returns its length.
- Initialize a count variable to 0, this count variable will count characters in the string.
- Now, the loop will run until the last element of the string is reached. once the index is greater than the string’s then the loop will terminate, and Except block will execute and print the length of the string.
Below is the implementation of the above approach:
Python3
def returnsLength(string): try : count = 0 while (string[count]): count + = 1 except : print ( "Length of the String : " , count) returnsLength( "w3wiki" ) # Contributed by SamyakJain |
‘
Time Complexity: O(n)
Auxiliary Space: O(1)
Use recursion:
Recursion is a technique in which a function calls itself with a modified version of its input until a certain condition is met. It can be a useful approach for solving problems that involve repetitive steps or when you need to perform a task a certain number of times.
Here is an example of a recursive function that calculates the length of a string using recursion:
Python3
def recursive_length(string): if string = = "": # base case: if the string is empty, the length is 0 return 0 else : # recursive case: remove the first character from the string and calculate the length of the remaining string return 1 + recursive_length(string[ 1 :]) print (recursive_length( "hello" )) # prints 5 |
5
Time complexity: O(n), where n is the length of the input string.
Auxiliary space:O(1),
Contact Us