eeskonivich
eeskonivich

Reputation: 131

Pairing elements without repeating

I am close to figuring out this problem but am hung on one one thing in particular. I am trying to pair/zip together elements in a list pair by pair, and then checking which value is greater. I just can't figure out how to pair these elements without repeating values.

[35,10,5,3,1,26,15]

I do NOT want:

[35,10], [10,5]

I DO want:

[35,10], [5,3]

Here is my code:

def queue_time(customers, n):
    time_left = 0
    max_val = max(customers[:n])
    total_time = int(max_val)
    other_customers = list(customers)
    other_customers.remove(max_val)

for idx, el in enumerate(other_customers):
    if max_val > 0:
        nxt_till_times = other_customers[idx:idx+n-1] 
        max_other_tills = max(nxt_till_times)
        max_val -= max_other_tills
        print nxt_till_times
    elif max_val == 0:
        max_val = max(customers[idx:idx+n])
        total_time += max_val
    elif max_val < 0:
        time_left = [-1*(max_val)]
        others_still = time_left + customers[idx+1:]
        max_val = max(others_still[:n])
        total_time += max_val

#print total_time
return total_time

queue_time([35,10,5,3,1,26,15], 3)

Upvotes: 0

Views: 54

Answers (2)

brianpck
brianpck

Reputation: 8254

Even simpler:

>>> l = [35,10,5,3,1,26,15]
>>> [l[i:i+2] for i in range(0, len(l)-1, 2)]
[[35, 10], [5, 3], [1, 26]]

This will cut off any odd-numbered elements of the list.

Upvotes: 1

Patrick Haugh
Patrick Haugh

Reputation: 61032

l = [35,10,5,3,1,26,15]
g = (i for i in l)
output = [(next(g), next(g)) for i in range(len(l)//2)]

g is a generator. This doesn't do anything with the last element of odd-length lists. That element is available at next(g)

Upvotes: 0

Related Questions