Home > Back-end >  Python3:How to return the amount of pairs of the same element in a list
Python3:How to return the amount of pairs of the same element in a list

Time:09-19

for example list of 7 elements {1,2,1,3,2,4,1} there are two pairs (1,1) and (2,2) with the rest being unmatched, how do I return the amount of pairs? (need to write my code under def

def sockMerchant(n, ar):

   

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    ar = list(map(int, input().rstrip().split()))

    result = sockMerchant(n, ar)

    fptr.write(str(result)   '\n')

    fptr.close()

CodePudding user response:

You can make use of defaultdict to keep the frequency of each number and divide each frequency by 2 to get the no: of pairs

from collections import defaultdict

def sockMerchant(n, ar):
    ddict = defaultdict(lambda: 0)
    for val in ar:
        ddict[val]  = 1
    noOfPairs = 0
    for item in ddict.values():
        noOfPairs  = item//2
    return noOfPairs

CodePudding user response:

In the example given, you have a set {}. Within a set, every value only occurs once.
If you have a list instead, you can do something like that to get all elements that appear more than once and divide the count by 2 to get the number of pairs.

import collections
yourlist = [1, 2, 1, 3, 2, 4, 1]
print([(item, count // 2) for item, count in collections.Counter(l).items() if count > 1])
  • Related