Perform String Shifts
Let’s break down the logic into multiple steps and write the Python code accordingly:
Initialize Variables: We’ll initialize a variable to keep track of the total shift, which will be positive for right shifts and negative for left shifts.
Calculate Total Shift: For each shift instruction in the given matrix, we’ll add or subtract the shift amount based on the direction. Right shifts will add to the total shift, and left shifts will subtract.
Normalize the Shift: If the total shift is greater than the length of the string, we need to reduce it using the modulo operation. This way, we handle shifts that are larger than the string’s length.
Perform the Shift: Based on the calculated total shift, we’ll perform the right shift or left shift on the string. This involves taking a slice of the string and rearranging the characters.
Here’s the code:
|
|
Explanation:
- The
total_shift
variable keeps track of the combined shift amount. - The loop iterates through the shift matrix, updating
total_shift
based on the direction. - We then normalize
total_shift
to ensure it is within the bounds of the string length. - Finally, we perform the shift by slicing and rearranging the string based on
total_shift
. Iftotal_shift
is zero, the string remains the same.