
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if a string can be obtained by rotating another string 2 places in Python
Suppose we have two strings s and t. We have to check whether we can get s by rotating t two place at any direction left or right.
So, if the input is like s = "kolkata" t = "takolka", then the output will be True as we can rotate "takolka" to the left side two times to get "kolkata".
To solve this, we will follow these steps −
- if size of s is not same as size of t, then
- return False
- right_rot := blank string
- left_rot := blank string
- l := size of t
- left_rot := left_rot concatenate t[from index l - 2 to end] concatenate t[from index 0 to l - 3]
- right_rot := right_rot concatenate t[from index 2 to end] concatenate t[from index 0 to 1]
- return true when (s is same as right_rot or s is same as left_rot) otherwise false
Let us see the following implementation to get better understanding −
Example
def solve(s, t): if (len(s) != len(t)): return False right_rot = "" left_rot = "" l = len(t) left_rot = (left_rot + t[l - 2:] + t[0: l - 2]) right_rot = right_rot + t[2:] + t[0:2] return (s == right_rot or s == left_rot) s = "kolkata" t = "takolka" print(solve(s, t))
Input
"kolkata", "takolka"
Output
True
- Related Articles
- Write a program in Java to check if a string can be obtained by rotating another string by 2 places
- Write a program in C++ to check if a string can be obtained by rotating another string by two places
- Check if a string can be repeated to make another string in Python
- Check if a string can be converted to another string by replacing vowels and consonants in Python
- Check if a string can be formed from another string using given constraints in Python
- Check If a String Can Break Another String in C++
- Check if given string can be formed by concatenating string elements of list in Python
- Program to check one string can be converted to another by removing one element in Python
- Check if string contains another string in Swift
- Check if a string is suffix of another in Python
- Check if a string can become empty by recursively deleting a given sub-string in Python
- Program to check whether one string can be 1-to-1 mapped into another string in Python
- How to check if a string can be converted to float in Python?
- Check if a string can be rearranged to form special palindrome in Python
- How can we check if specific string occurs multiple times in another string in Java?

Advertisements