|
| 1 | +#!/usr/bin/python3 |
| 2 | +''' |
| 3 | +Module that implements an algorithm to determine if a string has all unique characters. What if you |
| 4 | +cannot use additional data structures? |
| 5 | +''' |
| 6 | + |
| 7 | +import unittest |
| 8 | + |
| 9 | +def unique(string): |
| 10 | + '''checks if string input is unique |
| 11 | + Args: |
| 12 | + string (str): string to check |
| 13 | + ''' |
| 14 | + return len(set(string)) is len(string) |
| 15 | + |
| 16 | +def unique2(string): |
| 17 | + '''checks if string input is unique |
| 18 | + args: |
| 19 | + string (str): string to check |
| 20 | + ''' |
| 21 | + letters = {} |
| 22 | + for letter in string: |
| 23 | + letters[letter] = letters.get(letter, 0) + 1 |
| 24 | + if letters.get(letter) is not None and letters[letter] > 1: |
| 25 | + return False |
| 26 | + return True |
| 27 | + |
| 28 | +def unique3(string): |
| 29 | + '''checks if string input is unique, no new data structures |
| 30 | + args: |
| 31 | + string (str): string to check |
| 32 | + ''' |
| 33 | + new_string = sorted(string) |
| 34 | + for idx in range(len(new_string) - 1): |
| 35 | + if new_string[idx] == new_string[idx + 1]: |
| 36 | + return False |
| 37 | + |
| 38 | + return True |
| 39 | + |
| 40 | + |
| 41 | +class Test(unittest.TestCase): |
| 42 | + def test1(self): |
| 43 | + all_true = ["Nick", "world"] |
| 44 | + all_false = ["eee", "hello"] |
| 45 | + |
| 46 | + for idx in range(len(all_true)): |
| 47 | + self.assertTrue(unique(all_true[idx])) |
| 48 | + self.assertFalse(unique(all_false[idx])) |
| 49 | + |
| 50 | + def test2(self): |
| 51 | + all_true = ["Nick", "world", "Sue", "John", "abcdefghijklmnopqrstuvwxyz"] |
| 52 | + all_false = ["eee", "hello", "nicki", "johnny", "suuu"] |
| 53 | + |
| 54 | + for idx in range(len(all_true)): |
| 55 | + self.assertTrue(unique2(all_true[idx])) |
| 56 | + self.assertFalse(unique2(all_false[idx])) |
| 57 | + |
| 58 | + def test3(self): |
| 59 | + all_true = ["Nick", "world", "Sue", "John", "abcdefghijklmnopqrstuvwxyz"] |
| 60 | + all_false = ["eee", "hello", "nicki", "johnny", "suuu"] |
| 61 | + |
| 62 | + for idx in range(len(all_true)): |
| 63 | + self.assertTrue(unique3(all_true[idx])) |
| 64 | + self.assertFalse(unique3(all_false[idx])) |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + unittest.main() |
0 commit comments