June 22, 2018
Check if a string has all unique characters python
Problem
Given a string of characters. Implement an algorithm in Python to check if the string has all unique characters.
Solution
One solution is to get the unique characters in the string using a set. If the length of the input string is the same as the length of the set then the string has all unique characters. Another solution is to insert string characters into a dictionary. If there is at least one character with count greater than one then the input string does not have all unique characters.
Code
Here is the implementation in Python…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# Import python unit tests module import unittest # This function converts the input string to a set then # compares the length of the set with the length of the # input string. If the length is the same then the # string has all unique characters def allUniqueSet(mystr): return len(mystr) == len(set(mystr)) # This function uses the characters in the input string # as keys in a dictionary. The value associated with # a key is the count of that character in the string # If all keys have a count of one then all characters # are unique otherwise at least one character is repeated def allUniqueDic(mystr): dic = {} for c in mystr: dic[c] = 0 for c in mystr: dic[c]+= 1 for c, count in dic.items(): if count > 1: return False return True # This class uses python unit tests to test our code class Tests(unittest.TestCase): def test_case_01(self): self.assertTrue(allUniqueSet("isco")) def test_case_02(self): self.assertFalse(allUniqueSet("cisco")) def test_case_03(self): self.assertTrue(allUniqueDic("isco")) def test_case_04(self): self.assertFalse(allUniqueDic("cisco")) # Run test suite unittest.main() |
Thanks for visiting. For questions and feedback, please use the comments section below.