Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Explained - Kept simple solution in Clear category for Changing direction by Selindian
def changing_direction(elements: list) -> int:
if len(elements) == 1: return 0 # Handle special case - One element.
direction = list() # Create empty list
for idx in range(0, len(elements) - 1): # Loop over all elements by index
if elements[idx] > elements[idx + 1]: # If "direction" is down (element bigger than next one) ...
if not direction or direction[-1] == "down": # ... and direction empty or "down" ...
direction.append("up") # ... ... append "up".
elif elements[idx] < elements[idx + 1]: # Elif "direction" is up (element smaller than next one) ...
if not direction or direction[-1] == "up": # ... and direction empty or "up" ...
direction.append("down") # ... ... append "down".
return len(direction) - 1 # Return the len / sum of all words "up/down" -1.
print("Example:")
print(changing_direction([1, 2, 3, 4, 5]))
assert changing_direction([1, 2, 3, 4, 5]) == 0
assert changing_direction([1, 2, 3, 2, 1]) == 1
assert changing_direction([1, 2, 2, 1, 2, 2]) == 2
print("The mission is done! Click 'Check Solution' to earn rewards!")
Aug. 23, 2022
Comments: