42. Count the rises
A weather station writes down the temperature once an hour. Write a function count_rises(readings) that takes the
list of readings and returns how many times a reading is higher than the one just before it.
- Only a reading that is strictly higher counts: going from 6 to 6 isn't a rise.
- Each reading is compared with the one just before it, not with the first reading or the highest so far.
- A list with fewer than two readings has nothing to compare, so the answer is 0.
Example 1
Input
readings = [3, 5, 4, 6, 6, 8]Output
3Explanation3 to 5, 4 to 6, 6 to 8; 6 to 6 isn't one.
Example 2
Input
readings = [10, 1, 10, 1, 10]Output
2ExplanationEach 1 to 10 counts, though 10 isn't new.
Example 3
Input
readings = [5, 4, 3]Output
0ExplanationThe readings only ever go down.
Constraints
readingshas 0 to 100 whole numbers, each from -100 to 100.
Submit also runs 7 more tests you can't see.
Practises Lists (lesson 9).
- Loop over the indexes from 1, not 0, with
for i in range(1, len(readings)):, so every reading you look at has one before it. - Compare
readings[i]withreadings[i - 1], using>, not>=: an equal reading isn't a rise. - Starting at 0 would compare
readings[0]withreadings[-1], the last reading, and could count a rise that isn't there. With 0 or 1 readings the loop never runs, so you return 0.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
def count_rises(readings):
"""Count the readings higher than the one before.
readings: list of int; may be empty
Returns: int, how many times the next reading is
higher than the one before it
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.