How to Find the Stray Number in Python

0 min read 144 words

The challenge

You are given an odd-length array of integers, in which all of them are the same, except for one single number.

Complete the method which accepts such an array, and returns that single different number.

The input array will always be valid! (odd-length >= 3)

Examples

[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3

The solution in Python

Option 1:

def stray(arr):
    for x in arr:
        if arr.count(x) == 1:
            return x

Option 2:

def stray(arr):
    return min(arr, key=arr.count)

Option 3:

def stray(arr):
    return [x for x in set(arr) if arr.count(x) == 1][0]

Test cases to validate our solution

import codewars_test as test
from solution import stray

@test.describe("Fixed Tests")
def fixed_tests():
    @test.it('Basic Test Cases')
    def basic_test_cases():
        test.assert_equals(stray([1, 1, 1, 1, 1, 1, 2]), 2)
        test.assert_equals(stray([2, 3, 2, 2, 2]), 3)
        test.assert_equals(stray([3, 2, 2, 2, 2]), 3)
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