In this example, we will create a function in Python which will return the total number of duplicate pair of numbers within a list. For example, if we enter [0,0,0,0] into that function it will return 2 because there are two pairs of duplicate number within that list.

def duplicates(arr):
    
    global count
    count = 0
    while(len(arr) > 0):
        find = arr.pop(0) 
        for i in range(len(arr)) :
            if find == arr[i] :
                count += 1
                del arr[i]
                break
    return count

There is another solution written in Kotlin, if you are interested to know more then read this post.

In the next article, we will start another new Python project which will stay for at least a month, if you want to contribute to that project you can do so by creating a pool request on Github, stay tune and get ready for the new Python project starting from the next article onward!

Click to rate this post!
[Total: 0 Average: 0]
Please follow and like us:
error0

3 Comments

  1. I got here from Planet Python. Your code is correct but it does not follow Python conventions or uses the built-in Python features. For example, you don’t need global variables to solve this problem. I think you might be misleading junior programmers into writing low quality code. Here is a simpler way to solve the problem:

    def duplicates(arr):
    n_duplicates = 0
    while arr:
    afind = arr.pop(0)
    try:
    arr.remove(find)
    n_duplicates += 1
    except ValueError:
    pass
    return n_duplicates

    assert duplicates([0, 0, 0, 0]) == 2

    1. Thank you very much for your contribution, but are you sure it is a good idea to directly use a python list as the boolean logic to control the while loop?

  2. In addition to using an ill-advised global variable, your solution unexpectedly modifies the array passed in, and can look at array element multiple times. It’s much slower than it needs to be, on several levels, and doesn’t work for arbitrary sequences. Consider, for example:

    def duplicates(seq):
        from collections import Counter
        return sum(n//2 for n in Counter(seq).values())
    duplicates([0,0,0,0])
    # 2
    duplicates(‘abracadabra’)
    # 4

    And yes, using a bare list as a condition to control a while loop is better than comparing its length to zero, because the latter does far more wasted work, and the simple form is easier for an experienced Python developer to understand.

Leave a Reply

Your email address will not be published. Required fields are marked *