Table of Contents
method
Method 1: Use brute force
algorithm
Example
Output
Method 2: Use a while loop in a user-defined function
in conclusion
Home Backend Development Python Tutorial Python program: Find the minimum number of rotations required to get the actual string?

Python program: Find the minimum number of rotations required to get the actual string?

Aug 25, 2023 pm 09:21 PM
python string Number of spins

Python program: Find the minimum number of rotations required to get the actual string?

Understanding how to handle strings efficiently is a fundamental programming task that can significantly improve the performance of your code. Finding the minimum number of rotations required to produce a desired string from a rotated string is an interesting challenge in string manipulation. Situations such as text processing, cryptography, and data compression often involve this problem.

Consider the situation where the string is rotated to the right by a certain amount. The goal is to find the minimum number of rotations required to convert the string back to its original form. By finding the solution to this problem, we can learn more about the string structure and obtain useful information.

This article will examine two methods for determining the minimum number of rotations required to return the original string from a rotated string. Python, a flexible and popular programming language known for its readability and ease of use, will be used to put these technologies into practice.

method

To search in Python to get the minimum number of rotations of an actual string, we can follow two methods -

  • Use brute force.

  • Use while loops in user-defined functions.

Let’s examine these two methods -

Method 1: Use brute force

Use a brute force method to rotate the first string in all possible positions, then compare the second string to the rotated first string. We keep track of the minimum number of rotations required to obtain the second string by iterating over all feasible rotations. After the loop ends, if the minimum rotation variable is still infinity, it is impossible to get the second string by rotating the first string. If not, we return the minimum number of spins required. The time complexity of this method is O(n^2), where n is the length of the first string.

algorithm

The steps to search for the minimum number of rotations in Python to get the actual string are as follows -

Step 1- Create a function that takes two strings as input.

Step 2 - Create a variable with an initial value of infinity to keep track of the minimum number of spins required.

Step 3 - From 0 to the length of the first string, iterate through the possible values.

Step 4- The first string should be rotated by the current index position. This verifies that the second string and the rotated string are equal. If so, change the variable's value to the minimum value between the current minimum value and the current index.

Step 5− If the minimum rotation variable is still set to infinity, then -1 is returned (indicating that it is not feasible to retrieve the second string by rotating the first string).

Step 6 - If not, return the minimum rotation variable.

Example

def min_rotations_bf(s1, s2):
   min_rotations = float('inf')

   for i in range(len(s1)):
      rotated = s1[i:] + s1[:i]
      if rotated == s2:
         min_rotations = min(min_rotations, i)

   if min_rotations == float('inf'):
      return -1
   else:
      return min_rotations


# Example usage
s1 = "program"
s2 = "grampro"
bf_result = min_rotations_bf(s1, s2)

print("String 1:", s1)
print("String 2:", s2)
print("Minimum rotations (Brute Force):", bf_result)
Copy after login

Output

String 1: program
String 2: grampro
Minimum rotations (Brute Force): 3
Copy after login

Method 2: Use a while loop in a user-defined function

What works is to use the concatenated string to verify that the second string exists, rather than doing explicit string rotation. If the second string cannot be retrieved by rotation of the first string because the two strings are of different lengths, we return -1. By determining whether the second string is a substring of the concatenated string, we can figure out how many rotations are needed to separate the second string from the first. To determine the minimum number of rotations, if the second string is found as a substring, we calculate the index and divide it by the length of the first string. The time complexity of this method is O(n), where n is the length of the first string.

algorithm

The steps to search for the minimum number of rotations in Python to get the actual string are as follows -

Step 1- Create a function that takes two strings as input.

Step 2 - If the lengths of the two strings are not equal, return -1 (because the second string cannot be obtained by rotating the first string).

Step 3 - Create a temporary string by concatenating the first string with itself.

Step 4 - If the second string is a substring of the temporary string, return the minimum number of rotations required divided by the index of the second string in the temporary string Take the length of the first string.

Step 5− If not, return -1.

Example

def min_rotations_efficient(s1, s2):
   if len(s1) != len(s2):
      return -1

   rotations = 0
   n = len(s1)

   # Check for left rotations
   while rotations < n:
      if s1 == s2:
         return rotations
      s1 = s1[1:] + s1[0]
      rotations += 1

   # Check for right rotations
   s1 = s1[-1] + s1[:-1]
   rotations = 1

   while rotations <= n:
      if s1 == s2:
         return rotations
      s1 = s1[-1] + s1[:-1]
      rotations += 1

   return -1
# Example usage
s1 = "program"
s2 = "grampro"
efficient_result = min_rotations_efficient(s1, s2)

print("String 1:", s1)
print("String 2:", s2)
print("Minimum rotations ", efficient_result)
Copy after login

Output

String 1: program
String 2: grampro
Minimum rotations  3
Copy after login

in conclusion

In this article, we looked at two methods of calculating the minimum number of rotations required to convert a given string into another string. The second method uses the concatenated strings to check if the second string exists, while the brute force method rotates the first string every feasible number of positions. One can choose the best strategy to solve this problem in Python depending on the size of the input and the required efficiency. Thanks to these methods, you can now calculate the minimum number of rotations required to extract a target string from a given string.

The above is the detailed content of Python program: Find the minimum number of rotations required to get the actual string?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

See all articles