Python Forum

Full Version: How do I solve the second problem?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm stuck, I'm looking to know how to do the Second Problem. I'll share what I have for the first problem in hopes of getting help with the second problem.

First problem

Write a function video_ranges(datapoints, threshold) that outputs an array of time ranges during which the probability there is a cow in the frame meets or exceeds (greater than or equal to) the threshold.

1. datapoints = [(10, 0.1), (13, 0.2), (19, 0.9), (20, 0.8), (29, 0.1), (30, 0.1), (32, .9), (40, 0.1)] threshold = 0.8 Expected Result: [(19, 29), (32, 40)]
2. Likewise if datapoints were to be datapoints = [(10, 0.1), (19, 0.9)] threshold = 0.8 Expected result: [(19, None)]
3. datapoints = [(15, 0.4), (18, 0.9), (22, 0.8), (24, 0.5), (28, 0.9), (34, 0.8), (36, 0.9)] threshold = 0.8 Expected result:[(18, 24), (28, None)]

Second Problem
For the second problem, my initial instinct is to loop through, though it seems like it falls apart as a first step, especially if the list could be of any size and the parameters are to find the time span(s) where all exist at a given interval.

Write a function farm_ranges(all_datapoints, threshold), where all_datapoints is a list of arrays, one array per animal that Farmer MacDonald owns. The farm_ranges function should return a list of time ranges during which all animals were in the frame, where an animal is considered in the frame if the probability it is in the frame meets or exceeds the threshold.

I'm assuming all_datapoints.length >= 0, though this example only has a length of 2
    all_datapoints = [
       [(10, .1), (13, .2), (19, .9), (20, .8), (30, .1)], # [(19, 30)]
       [(15, .4), (18, .9), (22, .8), (24, .5), (28, .9), (34, .8), (36, .9)]
    ]
    threshold = 0.8;
    assert farm_ranges(all_datapoints, threshold) == [(19, 24), (28, 30)]
Code for the first problem
    def video_ranges(datapoints, threshold):
        res = []
        start = None
        end = None

        for dt in datapoints:
            tm, th = dt[0], dt[1]
            if th >= threshold and start is None:
                start = tm
            elif th < threshold and start is not None:
                end = tm
                res.append((start, end))
                start, end = None, None
        if start:
            res.append((start, None))
        return res
    
    threshold = 0.8
    datapoints1 = [(10, 0.1), (13, 0.2), (19, 0.9), (20, 0.8),
                   (29, 0.1), (30, 0.1), (32, 0.9), (40, 0.1)]
    
    output1 = video_ranges(datapoints1, threshold)
    print(output1)
    
    datapoints2 = [[10, 0.1], [19, 0.9]]
    output2 = video_ranges(datapoints2, threshold)
    print(output2)
Quote:
assert farm_ranges(all_datapoints, threshold) == [(19, 24), (28, 30)]
need code for farm_ranges