Home > Blockchain >  Making number pairs with for loop
Making number pairs with for loop

Time:07-29

I've been trying to get a desired result for the past few hours without success. I get lots of negative values printed out and I'm not sure if it's because of syntax or if I don't assign my variables properly.

I'm trying to get a set of two numbers that form a time period (the first representing the timestamp of the start of a clip and the second the end of the clip).

At first, I simply added 15 seconds before each list3 items for the first timestamp and 5 seconds after for the end of the timestamp making 20 seconds clips for each items in the list. Quickly enough I realized that some of those clips are overlapping. I'm trying to insert conditions so that this doesn't happen. If a clip is to overlap, then make it longer and ignore the next item's first timestamp (start of the next clip) and so on.

I have some code, but it renders mostly wrong numbers (undesired numbers, that is).

list3: [3, 20, 51, 76, 106, 126, 128, 129, 163, 181, 183, 185, 187, 236, 256, 273, 277, 281, 321, 322, 323, 325, 326]

for previous, current in zip(list3, list3[1:]):
    if current > 15:
        first_current = current-15
        second_current = current 5
        first_previous = previous-15
        second_previous = previous 5
        if second_previous 15 < first_current:
            print(f"{first_current}-{second_current}")
        else:
            print(f"{first_current-second_previous}-{second_current}")
**Desired output**:
    
    if previous_second   20 < current_first
    print current_first - 15
    
    else if previous_second   20 >= current_first
    print (current_first - previous_second)   5


EDIT: Desired output:
3 --> would be ignored since it is not above 15
20 --> 5-25
51 --> 36-56
76 --> 61-81
106 --> would normally be 91-111 but would be transformed (since the next item, 126, equals 111) into 126 5... so --> 91-131

CodePudding user response:

Here's what I think you're trying to say. It's like you have a list of events, and you have a recording that spans the entire interval. You want to extract a set of subsets of that recording, without having a bunch of dead time, but ensuring that you have covered at least 15 units before and 5 units after each event. Is that it?

If so, this does it:

list3 = [3, 20, 51, 76, 106, 126, 128, 129, 163, 181, 183, 185, 187, 236, 256, 273, 277, 281, 321, 322, 323, 325, 326]

intervals = []

for p in list3:
    # Is this point included in the current interval?  If so, 
    # extend the interval.
    base = max(0,p-15)
    if intervals and intervals[-1][0] <= base <= intervals[-1][1]:
        intervals[-1][1] = p 5
    else:
        intervals.append( [base,p 5] )

print(intervals)

Output:

[[0, 25], [36, 56], [61, 81], [91, 134], [148, 192], [221, 286], [306, 331]]
  • Related