Is there a way to optimize code for pairing the elements in a list and generate count of pairs

i want to optimize my code for following question

/*
A company sells dumbbells in pairs. These are weights for exercising. They receive a shipment of dumbbells weighing anywhere from 1 unit up to a certain maximum.

A pair can only be sold if their weights are sufficiently close: no greater than 1 unit difference.

Given an inventory of various weights, determine the maximum number of pairs the company can sell.

For example, if there are 2 dumbbells of weight 1, 4 of weight 2, 3 of weight 3 and 1 of weight 4, (arr = [2,4,3,1])

they can be paired as [1,1], [2,2], [2,2], [3,3], [3,4] for a total of 5 pairs.

i-th element is the number of dumbbells with a weight of i+1.
*/

For example :

if arr = [3,5,4,3]
number of pairs will be 7 as shown below:
initial array is to be converted to [3(1's),5(2's),4(3's),3(4's)] i.e [1,1,1,2,2,2,2,2,3,3,3,3,4,4,4]

Now we need to make pairs like this [1,1][1,2][2,2][2,2][3,3][3,3][4,4] remaining last 4 is left as it is single .so total number of pairs is 7

following is my solution for the same :

def taskOfPairing(arr):
    
    n = len(arr)
    count = 0
    newList = []
    
    for i, j in enumerate(arr):
        newList += [i + 1]*j
    print(newList) 
    count1 = 0
    k = 1
    newList.sort()
    n1 = len(newList)
    l=0
    r=0
    while r<n1:
        if newList[r]-newList[l] < k:
            count1 += 1
            newList.pop(l)
            newList.pop(r)
            n1 = len(newList)
            l=0
            r=0
            if len(newList) == 1:
                break
    return count1



arr= [3,5,4,3]
print(taskOfPairing(arr))

output = 7

however my output works but only when there is small numbers in list like arr = [3,5,4,3] or [2,4,3,1]

If i try putting large numbers in list for example , arr = [100000,200000,300000,400000] my code will not work and will cause a lot of delay in execution , can anyone let me know what i am doing wrong in this code .My apologies for asking naive questions .

Comments (0)