Changing Directions in Python

In Python, we can determine how many times a list changes direction by identifying peaks and valleys. A direction change occurs when the slope switches from increasing to decreasing (peak) or decreasing to increasing (valley).

Given a list like [2, 4, 10, 18, 6, 11, 13], the output should be 2 because the direction changes at index 3 (18 is a peak) and at index 4 (6 is a valley).

Algorithm

To solve this problem, we follow these steps:

  • Initialize a counter to track direction changes

  • Iterate through the list from index 1 to length-2

  • For each element, check if it's a peak or valley by comparing with neighbors

  • If nums[i-1] nums[i+1] (peak) or nums[i-1] > nums[i] (valley), increment counter

  • Return the total count

Implementation

def count_direction_changes(nums):
    count = 0
    for i in range(1, len(nums) - 1):
        if nums[i - 1] < nums[i] > nums[i + 1] or nums[i - 1] > nums[i] < nums[i + 1]:
            count += 1
    return count

# Test with the example
numbers = [2, 4, 10, 18, 6, 11, 13]
result = count_direction_changes(numbers)
print(f"Direction changes: {result}")
Direction changes: 2

How It Works

The algorithm examines each element and its immediate neighbors:

numbers = [2, 4, 10, 18, 6, 11, 13]

# Step by step analysis
for i in range(1, len(numbers) - 1):
    prev, curr, next_val = numbers[i-1], numbers[i], numbers[i+1]
    is_peak = prev < curr > next_val
    is_valley = prev > curr < next_val
    
    print(f"Index {i}: {prev} -> {curr} -> {next_val}")
    if is_peak:
        print(f"  Peak detected at {curr}")
    elif is_valley:
        print(f"  Valley detected at {curr}")
    else:
        print(f"  No direction change")
Index 1: 2 -> 4 -> 10
  No direction change
Index 2: 4 -> 10 -> 18
  No direction change
Index 3: 10 -> 18 -> 6
  Peak detected at 18
Index 4: 18 -> 6 -> 11
  Valley detected at 6
Index 5: 6 -> 11 -> 13
  No direction change

Alternative Using Class Structure

class DirectionCounter:
    def solve(self, nums):
        count = 0
        for i in range(1, len(nums) - 1):
            if nums[i - 1] < nums[i] > nums[i + 1] or nums[i - 1] > nums[i] < nums[i + 1]:
                count += 1
        return count

# Usage
counter = DirectionCounter()
result = counter.solve([2, 4, 10, 18, 6, 11, 13])
print(f"Total direction changes: {result}")
Total direction changes: 2

Conclusion

This algorithm efficiently counts direction changes by identifying peaks and valleys in a single pass. The time complexity is O(n) and space complexity is O(1), making it optimal for this problem.

Updated on: 2026-03-25T10:16:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements