Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to count the pairs of reverse strings
When it is required to count the pairs of reverse strings, we need to check if each string in a list has its reverse counterpart present. A simple iteration is used to compare strings with their reversed versions.
Example
Below is a demonstration of counting reverse string pairs ?
def count_reverse_pairs(string_list):
count = 0
visited = set()
for i in range(len(string_list)):
if i in visited:
continue
current_string = string_list[i]
reverse_string = current_string[::-1]
# Check if reverse exists in remaining elements
for j in range(i + 1, len(string_list)):
if j in visited:
continue
if string_list[j] == reverse_string:
count += 1
visited.add(i)
visited.add(j)
print(f"Pair found: '{current_string}' and '{reverse_string}'")
break
return count
# Example usage
my_list = ["abc", "cba", "hello", "olleh", "python", "world"]
print("The list is:")
print(my_list)
pairs_count = count_reverse_pairs(my_list)
print(f"\nTotal reverse string pairs: {pairs_count}")
The list is: ['abc', 'cba', 'hello', 'olleh', 'python', 'world'] Pair found: 'abc' and 'cba' Pair found: 'hello' and 'olleh' Total reverse string pairs: 2
Method Using Dictionary for Efficiency
For better performance with larger lists, we can use a dictionary to store string frequencies ?
def count_reverse_pairs_optimized(string_list):
string_count = {}
pairs = 0
# Count frequency of each string
for string in string_list:
string_count[string] = string_count.get(string, 0) + 1
processed = set()
for string in string_list:
if string in processed:
continue
reverse_string = string[::-1]
if string == reverse_string:
# Palindrome case
pairs += string_count[string] // 2
elif reverse_string in string_count and reverse_string not in processed:
# Regular reverse pair
pairs += min(string_count[string], string_count[reverse_string])
processed.add(string)
processed.add(reverse_string)
return pairs
# Example with duplicates
my_list = ["abc", "cba", "abc", "cba", "dad", "dad"]
print("The list is:")
print(my_list)
pairs_count = count_reverse_pairs_optimized(my_list)
print(f"Total reverse string pairs: {pairs_count}")
The list is: ['abc', 'cba', 'abc', 'cba', 'dad', 'dad'] Total reverse string pairs: 3
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Simple Iteration | O(n²) | O(n) | Small lists |
| Dictionary Method | O(n) | O(n) | Large lists with duplicates |
Conclusion
Use the simple iteration method for small lists where you want to see individual pairs. Use the dictionary method for better performance with larger datasets or when dealing with duplicate strings.
Advertisements
