Pendulum crossings
- O(n) · Medium
- Full plan
- Python
- JavaScript
- lists
- loops
- comparisons
Problem
Valeria hung a pendulum in the lab with a sensor that reads its position every tenth of a second: negative left of center, positive right of it, and 0 right at the center. She wants to know how many times it swung from one side to the other.
Write a function that takes the list of readings (integers or decimals; it may be empty) and returns how many crossings there were, as an integer. A crossing is a reading on the opposite side from the last reading that wasn't 0. A 0 belongs to no side: it isn't a crossing and doesn't change sides. So [2, 0, -3] has one crossing and [2, 0, 3] has none. The first reading that isn't 0 isn't a crossing either, since there's nothing to compare it with.
With [3, -2, -1, 4] there are two crossings: 3 to -2 and -1 to 4.
Examples
Crosses on every reading
[3, -2, 4, -1] → 3
Always on the same side
[1, 2, 3] → 0
A zero between different sides
[2, 0, -2] → 1
A zero between the same side
[2, 0, 3] → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def crossings(readings):
passJavaScript
function crossings(readings) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.