Python Program to Check if a string can be formed from another string by at most X circular clockwise shifts

Python Program to Check if a string can be formed from another string by at most X circular clockwise shifts

To determine if a string s1 can be formed from another string s2 by at most X circular clockwise shifts, you can implement the following steps:

  1. Check if both strings are of the same length.
  2. Concatenate s2 with itself. This step is done to simulate circular shifts easily.
  3. Iterate from 0 to X and check if s1 exists in s2 shifted by the current index. If it does at any iteration, then s1 can be formed from s2 by at most X circular clockwise shifts.

Here's the Python code for the above approach:

def canFormByShifts(s1, s2, X): if len(s1) != len(s2): return False # Concatenate s2 with itself to simulate circular shifts concatenated_s2 = s2 + s2 # Iterate and check if s1 exists in the shifted s2 for i in range(X + 1): if s1 == concatenated_s2[i:i+len(s1)]: return True return False # Driver code if __name__ == "__main__": s1 = "abc" s2 = "cab" X = 1 if canFormByShifts(s1, s2, X): print(f"'{s1}' can be formed from '{s2}' by at most {X} circular clockwise shifts.") else: print(f"'{s1}' cannot be formed from '{s2}' by at most {X} circular clockwise shifts.") 

The example above checks if the string "abc" can be formed from "cab" by at most 1 clockwise shift, and it prints the result accordingly.


More Tags

android-dialog node-mysql telnet eclipse-classpath reactive-streams unique-values emoticons azure-storage-files linechart google-cloud-firestore

More Programming Guides

Other Guides

More Programming Examples