0
def isRotation(s1, s2):
    return len(s1) == len(s2) and s2 in s1*2
isRotation("ABCD", "CDAB")
>> True

The code above was given as one of many ways to check if two strings are a rotation of each other. However, I don't understand why String1(s1) has to be multiplied by 2 in the code.

1
  • Well it is actually quite simple. In python str * 2 will just add a second copy of the string so "ABC" * 2 -> "ABCABC". From there, it can check if the original string is a substring of this string. Commented Feb 15, 2021 at 12:43

5 Answers 5

3

In python, multiplying strings is repeating the string, for example:

>>> 'abc'*2
'abcabc'
>>> 'abc'*4
'abcabcabcabc'

So in order to know if a string is a rotation of another string, you would need to multiplie it by 2, for example:

>>> 'bca' in 'abc'
False
>>> 'bca' in 'abc' * 2
True
Sign up to request clarification or add additional context in comments.

Comments

2

Multiplying a string by 2 will double the original string. And because s1 wraps around, regardless of its starting position the whole string can be found somewhere within twice its length

ABCDABCD
|||| DABC
||| CDAB
|| BCDA
| ABCD

Comments

1

Rotating a string is as good as chopping it at point of rotation and putting that chopped part at the end of string.

ABCDEFGH rotated 4 places to left is:

  1. Chop at 4-> ABCD EFGH
  2. Place at the end -> EFGHABCD

Python str*x gives you str concatenated to itself x times.

>>> a = 'String'
>>> a*2
'StringString'
>>> 

Putting these two points together with the fact that any string can be rotated by maximum amount equal to its length (when it becomes the original string) gives you the logic to check the rotated string's presence in str*2.

Comments

0

Understanding of your question is- To compare a string with the rotation string.

My approach to address the same would be.

1- To get the rotation string.

def rotate_str(strg, n):
    return strg[n:] + strg[:n]

length = 2 #can change this to whatever value suits to you or even pass this as arg.
print(rotate('SAMPLE', length)) 

2- compare strings.

   str1 = 'SAMPLE'
   str2 = rotate(str1, length)
   def compare_str(str1, str2):
       return str1 == str2

Comments

0

Here when we multiply s1 with 2. It returns s1s1 like if s1="ABCD", it will return "ABCDABCD", and in if s2 in s1*2 we are checking that if "CRAB" is in "ABCDABCD" which is true.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.