Python - Maximum consecutive elements percentage change

Python - Maximum consecutive elements percentage change

When we discuss the percentage change between consecutive elements in a list, we often refer to the relative difference between two consecutive values, calculated as:

Percentage Change=(Old ValueNew Value−Old Value​)×100

The task is to find the maximum percentage change between any two consecutive elements in a list.

Problem Statement:

Given a list of numbers, compute the maximum percentage change between two consecutive elements.

Example:

Input:

values = [100, 105, 102, 108, 115] 

Output:

Maximum Percentage Change: 6.48% (from 108 to 115) 

Step-by-Step Solution:

  1. Iterate Over the List: Traverse the list from the first element to the second last element.
  2. Compute Percentage Change for Each Pair: For each element i and the next element i+1, compute the percentage change using the formula given above.
  3. Identify the Maximum Percentage Change: Keep track of the maximum percentage change encountered so far.

Here's the Python code for this:

def max_percentage_change(values): # Check if the list has less than 2 values if len(values) < 2: return 0 # Initialize max percentage change to a very small number max_change = float('-inf') # Step 1: Iterate over the list for i in range(len(values) - 1): # Avoid division by zero if values[i] == 0: continue # Step 2: Compute percentage change for each pair change = ((values[i+1] - values[i]) / values[i]) * 100 # Step 3: Identify the maximum percentage change max_change = max(max_change, change) return max_change # Test values = [100, 105, 102, 108, 115] max_change = max_percentage_change(values) print(f"Maximum Percentage Change: {max_change:.2f}%") # Expected Output: Maximum Percentage Change: 6.48% 

Explanation:

For the list values:

  1. The percentage change between 100 and 105 is 100105−100​×100=5%.
  2. The percentage change between 105 and 102 is 105102−105​×100=−2.86%.
  3. The percentage change between 102 and 108 is 102108−102​×100=5.88%.
  4. The percentage change between 108 and 115 is 108115−108​×100=6.48%.

Thus, the maximum percentage change is 6.48%.

This approach efficiently calculates the percentage change between consecutive elements and ensures that we identify the maximum percentage change correctly.


More Tags

infinite-loop ios11 shared onsubmit price android-toast fbsdk integration devops privileges

More Programming Guides

Other Guides

More Programming Examples