Can you imagine deciphering a topographic map with just a sequence of letters? ⛰️ Let’s discover how to convert an alpinist’s steps into conquered summits with code.
🔮 Problem Statement
A fearless alpinist records each step of their expedition. Each “u” represents a step upwards, and each “d” a step downwards, always with respect to sea level. A mountain is a continuous region above sea level, and a valley, a similar depression below. The challenge is to determine how many mountains the alpinist has climbed (and descended), considering that both the ascent and descent of a mountain must end at sea level to be counted.
Parameters:
string path
: A string representing the alpinist’s route, where ‘u’ is a step up and ‘d’ is a step down.
Return Value:
int
: The number of mountains the alpinist visited during their route.
Example:
>>> counting_mountains('uudududuuddddudud')
1
>>> counting_mountains('ud')
1
>>> counting_mountains('du')
0
>>> counting_mountains('uuduudduu')
0
Additional Notes:
- For a valley or mountain to count as such, the alpinist must return to sea level.
- The alpinist will always take more than two steps before completing their route.
🧩 Step-by-Step Solution
Initially, we need to keep track of the alpinist’s altitude. To do this, we will use a variable psum
that will act as an accumulator. This variable is updated with each step, adding 1 if the step is upwards (‘u’) and subtracting 1 if it is downwards (‘d’). In addition, we will store each altitude in a list called sea_level
to have a complete history of the route.
psum = 0
sea_level = []
for p in path:
psum += 1 if p == 'u' else -1
sea_level.append(psum)
Once we have the altitude history, we can iterate through the sea_level
list to identify the mountains. A mountain is defined as a sequence of steps that begins and ends at sea level, with an intermediate altitude always positive. Therefore, we look for points where the current altitude is 0 (sea level) and the previous altitude was greater than 0.
mountains = 0
for i in range(1, len(path)):
if sea_level[i] == 0:
mountains += 1 if sea_level[i - 1] > 0 else 0
Finally, the function returns the number of mountains found.
Complete Solution:
def counting_mountains(path):
"level: medium; points: 5"
psum = 0
sea_level = []
for p in path:
psum += 1 if p == 'u' else -1
sea_level.append(psum)
mountains = 0
for i in range(1, len(path)):
if sea_level[i] == 0:
mountains += 1 if sea_level[i - 1] > 0 else 0
return mountains
🧠 Key Concepts
The solution fundamentally relies on accumulation, both for calculating the altitude at each step (psum
) and for counting mountains (mountains
). Accumulation is a ubiquitous technique in programming, allowing you to maintain state throughout an iterative process.
The use of the sea_level
list implies a form of understanding of temporal evolution. Instead of simply calculating the final result, we keep a complete record of the altitude at each step. This allows us to analyze the alpinist’s trajectory and detect the mountains with greater accuracy.
The iteration over the path
string and the sea_level
list is performed using implicit iterators in the for
loops. The abstraction offered by iterators facilitates the manipulation of data sequences without the need to manage indices manually.
Finally, conditionals (if
) are crucial for the mountain detection logic. The condition sea_level[i] == 0
checks if the alpinist has returned to sea level, and the condition sea_level[i - 1] > 0
checks if they came from a positive altitude (a mountain). Did you know that conditionals, at the level of computer architecture, are implemented through conditional jumps in machine code, altering the flow of program execution?
💫 Final Thoughts
This solution, although functional, could be optimized. For example, the sea_level
list might be unnecessary if we recalculated the previous altitude directly in the mountain counting loop. Also, validations could be added at the beginning of the function to verify the consistency of the input (path
), such as ensuring that it only contains the characters ‘u’ and ‘d’. Another possible improvement would be to generalize the function so that it can also count valleys.
We have seen how to transform a sequence of steps into a map of conquered mountains. 🚀 If you found this interesting, I invite you to explore other articles on my blog, where we unravel the mysteries of code and the logic that shapes the digital world. Dare to continue learning and to climb new summits in the universe of programming!