July 2, 2018
Check if a string is a rotation of another string in Python
Problem
Write a Python function that checks if two strings are rotation of each other
Solution
Rotating a string means inserting a number of characters from the end of the string to the beginning of the string. Any easy trick to check if two strings are rotation of each other is to concatenate one string to itself and then check if the other string is a substring in the concatenation
Example
Take a look at the following example
1 2 3 |
S1 = "Hello" S2 = "lloHe" S2 + S2 = "lloHelloHE" |
Note that Hello is a substring in lloHelloHe
Code
Here is the code in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# Import python unit tests module import unittest # This function returns true if the # input strings are rotation of # each other def isRotation(str1, str2): return len(str1) == len(str2) and str1 in str2 + str2 # This class uses python unit tests to test our code class Tests(unittest.TestCase): # Not the same length def test_case_01(self): self.assertFalse(isRotation("cisco", "ciscoo")) # Rotation of each other def test_case_02(self): self.assertTrue(isRotation("cisco", "cocis")) # Not a rotation of each other def test_case_03(self): self.assertFalse(isRotation("cisco", "occis")) # Run test suite unittest.main() |
If you run the test cases, you should get something like…
1 2 3 4 5 6 |
# ... # --------------------------------- # Ran 3 tests in 0.000s # OK # [Finished in 0.1s] |
Thanks for visiting. For questions, please use the comments section below