Program to check one string can be converted to other by shifting characters clockwise in Python

Suppose we have two strings p and q, and also have a number r, we have to check whether p can be converted to q by shifting some characters clockwise at most r times. So, as an example, "c" can be turned into "e" using 2 clockwise shifts.

So, if the input is like p = "abc", q = "ccc", r = 3, then the output will be True, as we can make "a" into "c" by using 2 clockwise shifts and then convert "b" into "c" by using 1 clockwise shift, for a total of 3 shifts.

To solve this, we will follow these steps −

  • if size of a is not same as size of b, then
    • return False
  • if k is same as 0 and a is not same as b, then
    • return False
  • su:= 0
  • for i in range 0 to size of a, do
    • v := ASCII of b[i] - ASCII of a[i]
    • if v>=0, then
      • su := su + v
    • otherwise,
      • su := su + v + 26
    • if su > k, then
      • return False
  • return True

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, a, b, k):
      if len(a) != len(b):
         return False
      if k == 0 and a != b:
         return False
         for i in range(len(a)):
            v = ord(b[i])- ord(a[i])
            if v>=0:
            if su>k:
               return False
         return True
ob = Solution()
print(ob.solve("abc", "ccc", 3))


"abc", "ccc", 3



Updated on: 05-Oct-2020


Kickstart Your Career

Get certified by completing the course

Get Started