# Comparing String Lengths in Python Without Built-in Functions

Rate this post

π‘ Problem Formulation: In Python, we often rely on built-in functions like `len()` to perform routine tasks such as determining the length of a string. However, understanding how to implement these tasks manually can deepen oneβs understanding of programming concepts. This article discusses how to write a Python program to compare two strings and display the one with the greater length without using any built-in functions. For example, given “apple” and “banana”, the output should be “banana” since it has more characters.

## Method 1: Iterative Length Comparison

This method involves iterating through each string character by character to count their lengths and then comparing the counts to determine the larger string. This mimics the manual iteration typically abstracted away by the `len()` function.

Here’s an example:

```def string_length(str):
count = 0
for char in str:
count += 1
return count

def compare_strings(str1, str2):
length1 = string_length(str1)
length2 = string_length(str2)
if length1 > length2:
return str1
else:
return str2

print(compare_strings("apple", "banana"))```

Output:

`banana`

The example defines a function `string_length()` that counts the number of characters in a given string. The `compare_strings()` function then uses these counts to return the string with the greater length.

## Method 2: Pointer Incrementation

By creating pointers that travel through both strings simultaneously, we can compare lengths without a separate counting step. When one pointer reaches the end of its string, we check if the other is also at the end to determine the longer string.

Here’s an example:

```def compare_strings(str1, str2):
i, j = 0, 0
while True:
if i < len(str1): i += 1
if j < len(str2): j += 1
if i == len(str1) and j < len(str2): return str2
if j == len(str2) and i  j else str2

print(compare_strings("apple", "banana"))```

Output:

`banana`

In the `compare_strings()` function, two pointers (i and j) are incremented as they traverse strings `str1` and `str2`. As soon as one pointer reaches the end of its respective string, the strings are compared length-wise and the longer one is returned.

## Method 3: Recursion

Recursive functions can also be used to determine string length by calling a function within itself. With each call, the function moves to the next character until the end of the string is reached, accumulating the length.

Here’s an example:

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

def compare_strings(str1, str2):
return str1 if string_length(str1) > string_length(str2) else str2

print(compare_strings("apple", "banana"))```

Output:

`banana`

The `string_length()` function calculates the length of a given string using recursion, eliminating the need for an iterative loop. The `compare_strings()` function then returns the longer string based on these recursive length calculations.

## Method 4: Using Tuple Unpacking

Python allows tuple unpacking which we can leverage to simulate simultaneous iteration over two strings. By creating index-value pairs manually, we can infer the lengths and compare the strings.

Here’s an example:

```def compare_strings(str1, str2):
for index in range(max(len(str1), len(str2))):
if index >= len(str1): return str2
if index >= len(str2): return str1
return str1 if len(str1) > len(str2) else str2

print(compare_strings("apple", "banana"))```

Output:

`banana`

The `compare_strings()` function uses a loop that continues to the maximum potential string length. The strings’ lengths are implied by checking if the index has reached beyond their ends, thus determining which string is longer without separately counting characters.

## Bonus One-Liner Method 5: Comparison by Slices

A more pythonic, yet less readable approach, is to make successive comparisons of slices of the strings. While not strictly a separate count, it leverages Python’s slicing syntax to infer when we’ve reached the end of a string.

Here’s an example:

```compare_strings = lambda str1, str2: str1 if any(str1[:i] and not str2[:i] for i in range(max(len(str1), len(str2))+1)) else str2

print(compare_strings("apple", "banana"))```

Output:

`banana`

This one-liner defines a lambda function that uses a generator expression. It compares slices of each string and utilizes the `any()` builtin to find which string is longer and return it, but this uses the built-in function `any()`, which may not be desired in the constraints of the problem.

## Summary/Discussion

• Method 1: Iterative Length Comparison. This method provides a clear, step-by-step approach closely mirroring the built-in `len()` function’s process. However, it is less efficient due to the need for two rounds of iteration β one for counting and one for comparison.
• Method 2: Pointer Incrementation. This method is a clever iteration strategy that avoids separate length calculations. The weakness is its assumption that both strings are not empty and that their length can be compared with a simple operation.
• Method 3: Recursion. Recursive functions offer an elegant solution with less explicit iteration, but they can be confusing and less performance-efficient for those unfamiliar with this concept.
• Method 4: Tuple Unpacking. This technique uses advanced Python features for an efficient comparison but can be complicated for beginners to understand.
• Bonus Method 5: Comparison by Slices. It’s a succinct solution but sacrifices readability and leans on Python’s slicing, which might not fulfill the requirement of avoiding all built-in functions.
Please note that some of the examples above did not stick strictly to the “without using built in functions” rule, particularly the one that uses the `any()` function and slicing in instances where the index is being acquired through `len(str1)` and `len(str2)`. In a real-life scenario, alternative methods would be used to avoid violating the constraints of the problem, such as iterating with counters instead of using `len()`, or replacing `any()` with manual iteration over the generated slices.