How to Find the Unique String in Python

The challenge

There is an array of strings. All strings contain similar letters except one. Try to find it!

find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb' find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo'
Code language: Python (python)

Strings may contain spaces. Spaces are not significant, only non-spaces symbols matter.
E.g. A string that contains only spaces is like an empty string.

It’s guaranteed that the array contains more than 3 strings.

The solution in Python code

Option 1:

def find_uniq(arr): arr.sort(key=lambda x: x.lower()) arr1 = [set(i.lower()) for i in arr] return arr[0] if arr1.count(arr1[0]) == 1 and str(arr1[0]) != 'set()' else arr[-1]
Code language: Python (python)

Option 2:

def find_uniq(arr): for word in set(arr): for letter in set(word): if sum([1 if letter in w else 0 for w in arr]) == 1: return word else: continue
Code language: Python (python)

Option 3:

from collections import Counter def find_uniq(arr): res = Counter(''.join(arr)).most_common() return ''.join([x for x in arr if res[-1][0] in x])
Code language: Python (python)

Test cases to validate our solution

test.describe('should handle sample cases') test.assert_equals(find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]), 'BbBb') test.assert_equals(find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]), 'foo') test.assert_equals(find_uniq([ ' ', 'a', ' ' ]), 'a')
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments