1. Home
  2. Docs
  3. Exercises
  4. Sets Exercises – Python

Sets Exercises – Python

In this section you find Sets Exercises,
 

Try yourself first before checking the solutions.

 

Exercise 1:
 

Find whether a given string has unique characters,

return True, if duplicates return False

sample input

‘just’ => has unique characters

Alexander => has duplicates
 

Solution:

 

def is_unique(given_string):
    
    #creating an empty set

    chars_set = set()
    
    for char in given_string:

        #if char already in set 
        #its duplicate
        
        if char in chars_set:
            
            return False
        
        else:

            #char not in set, add it

            chars_set.add(char)
    
    #if no duplicates
    
    return True

s1 = 'just'

s2 = 'Alexander'

print(is_unique(s1))

print(is_unique(s2))

output:

True
False