Home > Backend Development > Python Tutorial > Python - Minimum sum of consecutive characters

Python - Minimum sum of consecutive characters

王林
Release: 2023-09-08 19:37:02
forward
1505 people have browsed it

Python - 连续字符的最小和

Introduction

In Python programming, the task of finding the minimum sum of consecutive characters in each string can be a common problem in different applications. The goal is to identify the substring that yields the smallest sum when considering the ASCII values ​​of its characters. This article explores different ways of approaching problems using Python. The article first introduces the importance of finding the minimum sum of consecutive characters and its relevance in solving practical problems. It emphasizes the importance of efficient algorithms in optimizing minimum sum calculations.

Python − Minimum sum of consecutive characters

In Python programming, the task of finding the smallest complete contiguous character in each string involves distinguishing the substrings within the string that yield the smallest whole when considering the ASCII values ​​of their characters. The goal is to determine the substring that yields the smallest overall among all possible substrings.

In order to solve this problem, we can utilize different methods and approaches in Python. These methods include repeating through a string and counting the integer parts of consecutive substrings, comparing them, and keeping track of the smallest integer encountered. By considering the ASCII value of the character and performing appropriate calculations, it is possible to discover the substring that yields the smallest integer.

Python provides some built-in functions and features that facilitate the execution of these methods. Functions like ord() can be used to get the ASCII value of a character, while loops and conditional statements allow us to iterate through the string and perform the necessary calculations. By utilizing these features, we were able to successfully solve the problem and get the required minimum sum of consecutive characters.

Method 1: Use brute force cracking

The primary approach may be a brute force strategy consisting of repeating all possible sequential substrings in a given string. Here are the steps to resolve the issue using this method:

algorithm

Step 1:Initialize the variable min_sum with a huge value (e.g. infinity) to keep track of the minimum sum.

Step 2: Use two nested loops to emphasize all possible substrings of the given string. The outer loop determines the starting index of the substring, and the inner loop determines the ending index.

Step 3: Use Python's built-in sum() function or compute the entirety of the current substring by physically emphasizing the substring and including the character value. p>

Step 4: Compare the calculated overall to the current minimum sum (min_sum). If the calculated integrity is the minimum, min_sum is promoted to the unused minimum integrity.

Step 5: Repeat steps 3 and 4 for all substrings.

Step 6:Return the final minimum sum (min_sum) as the result.

Example

def minimum_sum_of_consecutive_chars(string):
    min_sum = float('inf')
    length = len(string)

    for i in range(length):
        for j in range(i, length):
            substring = string[i:j+1]
            current_sum = sum(ord(c) for c in substring)
            min_sum = min(min_sum, current_sum)

    return min_sum

    
string = "abcde"
print(minimum_sum_of_consecutive_chars(string))
Copy after login

Output

97
Copy after login
Copy after login
Copy after login

Method 2: Use dynamic programming

The second method uses dynamic programming to solve the minimum sum problem of consecutive characters more efficiently. This method avoids double calculations by storing the results of subproblems in memory tables. Here are the steps to implement this approach:

algorithm

Step 1:Define user-defined functions. Determine the length of the string.

Step 2:Initialize the basic situation. Set memo[i][i] (corner-to-corner component) to the ASCII value of the character at list i in the string.

Step 3: Emphasize all substrings of length l from 2 to the length of the string. For each substring, highlight all starting lists

Step 4:Calculate the sum of the current substring and update the corresponding paragraph in the memory table.

Step 5: Finally, return the smallest whole from the upper right corner of the memo table.

Example

def minimum_sum_of_consecutive_chars(string):
    length = len(string)
    memo = [[0] * length for _ in range(length)]

    for i in range(length):
        memo[i][i] = ord(string[i])

    for l in range(2, length + 1):
        for i in range(length - l + 1):
            j = i + l - 1
            memo[i][j] = memo[i][j - 1] + ord(string[j])

    return min(memo[i][j] for i in range(length) for j in range(i, length))

  
string = "abcde"
print(minimum_sum_of_consecutive_chars(string))
Copy after login

Output

97
Copy after login
Copy after login
Copy after login

Method 3: Use sliding window

The third method, called the sliding window method, optimizes the previous method and improves efficiency by eliminating redundant calculations. Instead of iterating over all possible substrings, this approach maintains a sliding window representing the substring currently under consideration. Here are the steps to implement the sliding window approach:

algorithm

Step 1:Initialize two pointers at the beginning of the string, begin and conclusion.

Step 2: Initialize the variable current_sum to track the sum of the current window.

Step 3: Initialize min_sum and make it infinite

Step 4: Return the minimum sum (min_sum) as the result.

Example

def minimum_sum_of_consecutive_chars(string):
    start = 0
    end = 0
    length = len(string)
    current_sum = ord(string[0])
    min_sum = float('inf')

    while end < length:
        if current_sum < min_sum:
            min_sum = current_sum

        end += 1

        if end < length:
            current_sum += ord(string[end])

        while current_sum >= min_sum and start < end:
            current_sum -= ord(string[start])
            start += 1

    return min_sum

    
string = "abcde"
print(minimum_sum_of_consecutive_chars(string))
Copy after login

Output

97
Copy after login
Copy after login
Copy after login

in conclusion

We looked at three different approaches to understanding the problem of minimum consecutive characters in Python. We discuss a brute force constraint approach, a dynamic programming approach, and a sliding window approach. Each method has its own steps, code execution and output, demonstrating different algorithmic approaches to the problem. By understanding these methods, you can choose the solution that best suits your specific needs and optimize the calculation of minimum consecutive characters in Python.

The above is the detailed content of Python - Minimum sum of consecutive characters. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template