MAUCA
MAUCA

Reputation: 59

Check if a string has unique characters excluding whitespace

I'm practicing questions from Cracking the coding interview to become better and just in case, be prepared. The first problem states: Find if a string has all unique characters or not? I wrote this and it works perfectly:

def isunique(string):
    x = []
    for i in string:
        if i in x:
            return False
        else:
            x.append(i)
    return True

Now, my question is, what if I have all unique characters like in: 'I am J' which would be pretty rare, but lets say it occurs by mere chance, how can I create an exception for the spaces? I a way it doesn't count the space as a character, so the func returns True and not False?

Upvotes: 0

Views: 1651

Answers (5)

cs95
cs95

Reputation: 402962

An elegant approach (YMMV), with collections.Counter.

from collections import Counter

def isunique(string):
    return Counter(string.replace(' ', '')).most_common(1)[0][-1] == 1

Alternatively, if your strings contain more than just whitespaces (tabs and newlines for instance), I'd recommend regex based substitution:

import re
string = re.sub(r'\s+', '', string, flags=re.M)

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53545

And... a pool of answers is never complete unless there is also a regex solution:

def is_unique(string):
    import re
    patt = re.compile(r"^.*?(.).*?(\1).*$")
    return not re.search(patt, string)

(I'll leave the whitespace handling as an exercise to the OP)

Upvotes: 0

Aaditya Ura
Aaditya Ura

Reputation: 12679

Now no matter how space or how many special characters in your string , it will just count the words :

import re
def isunique(string):
    pattern=r'\w'
    search=re.findall(pattern,string)
    string=search
    x = []
    for i in string:
        if i in x:
            return False
        else:
            x.append(i)
    return True



print(isunique('I am J'))

output:

True

without space words test case :

print(isunique('war'))
True

with space words test case:

print(isunique('w a r'))
True

repeating letters :

print(isunique('warrior'))
False

Upvotes: 2

DGVIP
DGVIP

Reputation: 1

Simple solution

def isunique(string):
    return all(string.count(i)==1 for i in string if i!=' ')

Upvotes: -1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48110

Create a list of characters you want to consider as non-characters and replace them in string. Then perform your function code.

As an alternative, to check the uniqueness of characters, the better approach will be to compare the length of final string with the set value of that string as:

def isunique(my_string):
    nonchars = [' ', '.', ',']
    for nonchar in nonchars:
        my_string = my_string.replace(nonchar, '')
    return len(set(my_string)) == len(my_string)

Sample Run:

>>> isunique( 'I am J' )
True

As per the Python's set() document:

Return a new set object, optionally with elements taken from iterable. set is a built-in class. See set and Set Types — set, frozenset for documentation about this class.

Upvotes: 0

Related Questions