![]() |
In Python, the length of a string can be calculated without using any library function by iterating through the characters of the string and counting them manually. This process involves creating a counter variable and incrementing it for each character encountered in the string. In this article, we will explore four different approaches to calculating the length of a string without using the library function. Get the Length of Text Without Using Inbuild Python Library FunctionBelow are some of the ways by which we can calculate the length of the string without using a library function in Python. Calculate the Length of the String Using for LoopThe below Python code defines a user-defined function lengthOfString that calculates the length of a given string using a for loop. It iterates through each character in the input string, incrementing a counter variable (length) for each character, and returns the final count as the length of the string. Python3
Output
Length of the string: 13 Time complexity: O(n) Calculate the Length of the String Using lambda FunctionThe below Python code defines a user-defined function length_of_string that calculates the length of a given string using lambda function and mapping. We can use map and lambda to create a list of 1’s with the same length as the string and then use the sum function to add up those 1’s, giving us the length of the string. Python3
Output
Length of the string: 13 Space complexity: O(n) Calculate the Length of the String Using enumerate FunctionThe below code defines a function length_of_string_enumerate that calculates the length of the given string “GeeksforGeeks” using the enumerate function in a loop. The output is then printed, showing the length of the string as 13. Python3
Output
Length of the string: 13 Space Complexity: O(n) Time complexity: O(1) Calculate the Length of the String Using RecursionThe below Python code defines a user-defined function lengthOfString that calculates the length of a given string using recursion. This function returns a value that calls itself until the index has not reached its limit. Python3
Output
Length of the string: 13 Time Complexity: O(n) Space complexity: O(n) ConclusionIn conclusion, these four approaches provide different methods for calculating the length of a string in Python without using library functions. The for loop and lambda function approaches offer simplicity and efficiency, with O(n) time complexity. The enumerate function demonstrates a concise way to calculate the length with O(1) space complexity. The recursive approach, while clear in concept, comes with higher space complexity (O(n)) due to the recursive calls |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |