Python - Check if two strings are Rotationally Equivalent

Python - Check if two strings are Rotationally Equivalent

Checking if two strings are rotationally equivalent means determining if one string can be obtained from the other by rotating the characters. For example, the strings "abcde" and "cdeab" are rotationally equivalent.

Here's how to check this in Python:

Objective:

Determine if two given strings, str1 and str2, are rotationally equivalent.

Method 1: Using String Concatenation

One of the most straightforward techniques involves concatenating one string to itself and then checking if the other string is a substring of this concatenated string.

str1 = "abcde"
str2 = "cdeab"

def are_rotationally_equivalent(str1, str2):
    if len(str1) != len(str2):
        return False

    return str2 in str1 + str1

print(are_rotationally_equivalent(str1, str2))  # Output: True

Method 2: Rotational Checks

Another method involves rotating str1 iteratively and checking if any of these rotations match str2.

str1 = "abcde"
str2 = "cdeab"

def are_rotationally_equivalent(str1, str2):
    if len(str1) != len(str2):
        return False

    for i in range(len(str1)):
        if str1[i:] + str1[:i] == str2:
            return True
    return False

print(are_rotationally_equivalent(str1, str2))  # Output: True

Tips:

  1. Before checking the rotational equivalence, it's good to check if both strings have the same length. If they don't, they can't be rotationally equivalent.
  2. Method 1, using string concatenation, is generally more efficient for this kind of check. This is because you only concatenate and then check for a substring, while Method 2 potentially builds n different strings where n is the length of str1.

Choose the method that best fits the specific requirements and constraints of your problem!


More Tags

terraform sqlanywhere android-radiobutton string-formatting hyperledger mariadb signalr-hub statusbar timeoutexception rerender

More Programming Guides

Other Guides

More Programming Examples