Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,984 questions

51,928 answers

573 users

How to check if a string contains only unique characters in Python

4 Answers

0 votes
def contains_unique_chars(s): 
    char_exist = [False] * 128
  
    for i in range(0, len(s)): 
        val = ord(s[i]) 
        if char_exist[val]: 
            return False
  
        char_exist[val] = True
  
    return True
  

s = "+python"
print(contains_unique_chars(s)) 

 
  
 
'''
run:
 
True
 
'''

 



answered Dec 28, 2019 by avibootz
0 votes
def contains_unique_chars(s): 
    b = 0
    
    for i in range(len(s)): 
        val = ord(s[i]) - ord('a') 
        print("%3d %27s %9d %2d" % (val, bin(b), 1 << val, b & 1 << val))
        if (b & (1 << val)) > 0: 
            return False
        b |= (1 << val) 
    return True
  

s = "apythona"
print(contains_unique_chars(s)) 

 
  
 
'''
run:
 
  0                         0b0         1  0
 15                         0b1     32768  0
 24          0b1000000000000001  16777216  0
 19 0b1000000001000000000000001    524288  0
  7 0b1000010001000000000000001       128  0
 14 0b1000010001000000010000001     16384  0
 13 0b1000010001100000010000001      8192  0
  0 0b1000010001110000010000001         1  1
False
 
'''

 



answered Dec 28, 2019 by avibootz
0 votes
def contains_unique_chars(s):
    return len(s) == len(set(s))


s = "pythonp"

print(contains_unique_chars(s)) 



'''
run:

False

'''

 



answered Jan 7, 2020 by avibootz
0 votes
def contains_unique_chars(s):
    return len(s) == len(frozenset(s))


s = "pythonp"

print(contains_unique_chars(s)) 



'''
run:

False

'''

 



answered Jan 7, 2020 by avibootz

Related questions

1 answer 162 views
2 answers 265 views
1 answer 155 views
2 answers 192 views
2 answers 266 views
1 answer 158 views
...