Comparing String Lengths in Python Without Built-in Functions

Rate this post

πŸ’‘ Problem Formulation: How can you take two strings as input in Python and determine which string is larger based on length, without utilizing built-in functions? Imagine receiving inputs such as string1 = “Hello” and string2 = “Greetings!” and needing to display “Greetings!” as output since it is the longer string.

Method 1: Iterate and Count Characters

This method involves iterating through each character in both strings to count their lengths and then comparing these counts to identify the larger string. By not using Python’s len() function, we ensure manual processing of string length calculation.

Here’s an example:

string1 = "Hello"
string2 = "Worldliness"

count1, count2 = 0, 0
for char in string1:
    count1 += 1
for char in string2:
    count2 += 1

if count1 > count2:
    print(string1)
elif count2 > count1:
    print(string2)
else:
    print("Strings are of equal length")

Output will display: “Worldliness”

In this snippet, we create two counters count1 and count2, which are incremented as the for loop iterates over each character of the strings. Finally, we compare these counters to determine the string with greater length.

Method 2: Compare with Character Pointers

With this approach, we use two pointers to iterate over both strings simultaneously until one string ends. The string with remaining characters is the longer one.

Here’s an example:

string1 = "Innovation"
string2 = "Creativity"

index = 0
while index < len(string1) and index = len(string1) and index = len(string2) and index < len(string1):
    print(string1)
else:
    print("Strings are of equal length")

Output will display: “Innovation”

This method uses index as a pointer to compare characters of both strings. Once one string ends, the loop exits, and a conditional check determines and prints the longer string, or notes equality in length.

Method 3: Recursion to Determine String Length

This technique employs recursion to find the string lengths by recursively calling a function that cuts down the strings until they’re empty, using this to count their lengths.

Here’s an example:

def string_length(str, count=0):
    if str == '':
        return count
    else:
        return string_length(str[1:], count + 1)

string1 = "Asynchronous"
string2 = "Synchronous"

length1 = string_length(string1)
length2 = string_length(string2)

if length1 > length2:
    print(string1)
elif length2 > length1:
    print(string2)
else:
    print("Strings are of equal length")

Output will display: “Asynchronous”

The recursive function string_length calculates the length of each string by taking a string and a counter as arguments. It returns the counter when the string is empty, giving us the length to compare.

Method 4: String Expansion Comparison

This creative method converts the strings into lists by expanding them character by character and compares the lists’ sizes.

Here’s an example:

string1 = "Developer"
string2 = "Programmer"

list1 = [char for char in string1]
list2 = [char for char in string2]

size1 = 0
for _ in list1:
    size1 += 1
size2 = 0
for _ in list2:
    size2 += 1

if size1 > size2:
    print(string1)
elif size2 > size1:
    print(string2)
else:
    print("Strings are of equal length")

Output will display: “Programmer”

This snippet demonstrates expanding strings into lists and using loops to determine their sizes. The longer list correlates to the longer string, which is then printed.

Bonus One-Liner Method 5: Comparing String Unpacking

This one-liner approach makes use of the extended unpacking feature in Python to determine which string creates a longer list of characters.

Here’s an example:

string1 = "Expression"
string2 = "Thought"

larger_string = string1 if [*string1] > [*string2] else string2
print(larger_string)

Output will display: “Expression”

With the unpacking operator *, we turn the strings into lists and then use the greater-than operator to compare the lists implicitly by their lengths, revealing the longer string.

Summary/Discussion

  • Method 1: Character Iteration. Easy to implement. Performance decrease with long strings.
  • Method 2: Pointer Comparison. Less code intensive. Can be confusing to read and understand.
  • Method 3: Recursive Length Calculation. Elegant solution. Potential for stack overflow with very long strings.
  • Method 4: List Conversion. Intuitive list operations. Extra memory usage due to list creation.
  • Method 5: Unpacking Comparison. Concise one-liner. Less readable and may not work on older Python versions.