Skip to content
ExamSpine

Lesson 6.2 · Write it

Fix the dry spell counter

A functionPython or Java13 tests, 9 of them hidden

On a phone? Put the lines in order instead

A weather station records the rain on each day, in whole millimetres, in a list (an array in Java). A dry spell is a run of days in a row with 0 mm of rain. A classmate wrote this function to return the length of the longest dry spell, but it gives a wrong answer for some lists.

def longest_dry(rain):
    longest = 0
    run = 0
    for mm in rain:
        if mm == 0:
            run = run + 1
        else:
            if run > longest:
                longest = run
            run = 0
    return longest
public static int longestDry(
        int[] rain) {
    int longest = 0;
    int run = 0;
    for (int mm : rain) {
        if (mm == 0) {
            run = run + 1;
        } else {
            if (run > longest) {
                longest = run;
            }
            run = 0;
        }
    }
    return longest;
}

Trace the classmate's function by hand with the list 3, 0, 0, 0 to find the bug. Then write a version that is always right.

  1. Return the number of days in the longest dry spell. If no day is dry, return 0.
  2. The list always has at least 1 day and at most 31 days.
  3. Every value is a whole number from 0 to 500.

Only the number your function returns is checked.

def longest_dry(rain: list[int]) -> int

Examples

Your function is tested on 13 cases: the 4 examples below, and 9 hidden ones that check the rules above.

  • longest_dry([3, 0, 0, 0]) should return 3: the longest spell runs to the end of the list
  • longest_dry([0, 5, 0]) should return 1: two spells of 1 day, split by a wet day: they are not in a row
  • longest_dry([0, 0, 7, 0]) should return 2: the longer spell comes first, before the wet day
  • longest_dry([4, 2, 6]) should return 0: no dry day at all (rule 1)

public static int longestDry(int[] rain)

Checking whether Java answers can run here.

Examples

Your function is tested on 13 cases: the 4 examples below, and 9 hidden ones that check the rules above.

  • longestDry(new int[]{3, 0, 0, 0}) should return 3: the longest spell runs to the end of the list
  • longestDry(new int[]{0, 5, 0}) should return 1: two spells of 1 day, split by a wet day: they are not in a row
  • longestDry(new int[]{0, 0, 7, 0}) should return 2: the longer spell comes first, before the wet day
  • longestDry(new int[]{4, 2, 6}) should return 0: no dry day at all (rule 1)
solution.pySolution.java