Sum of Array Singles in Python

0 min read 140 words

The challenge

You are given an array of numbers in which two numbers occur once and the rest occur only twice. Your task is to return the sum of the numbers that occur only once.

For example, repeats([4,5,7,5,4,8]) = 15 because only the numbers 7 and 8 occur once, and their sum is 15. Every other number occurs twice.

The solution in Python code

Option 1:

def repeats(arr):
    count = []
    for i in arr:
        if i not in count:
            count.append(i)
        else:
            count.remove(i)
            
    return sum(count)

Option 2:

def repeats(arr):
    return sum([x for x in arr if arr.count(x) == 1])

Option 3:

repeats=lambda a:2*sum(set(a))-sum(a)

Test cases to validate our solution

test.it("Basic tests")
test.assert_equals(repeats([4,5,7,5,4,8]),15)
test.assert_equals(repeats([9, 10, 19, 13, 19, 13]),19)
test.assert_equals(repeats([16, 0, 11, 4, 8, 16, 0, 11]),12)
test.assert_equals(repeats([5, 17, 18, 11, 13, 18, 11, 13]),22)
test.assert_equals(repeats([5, 10, 19, 13, 10, 13]),24)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags