Skip to content

Commit 73fb371

Browse files
authored
Merge pull request #17 from miguelHx/master
Miguel solution to 1.1 [Python]
2 parents a160ef6 + 22e95b5 commit 73fb371

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
"""
2+
Python version 3.7.0
3+
1.1
4+
Implement an algorithm to determine if a string has all unique characters.
5+
What if you cannot use additional data structures?
6+
What if the input string is empty?
7+
I assume that the user will input a non-empty string
8+
If the string is empty, then raise a ValueError exception
9+
If the input is NOT a string, then raise a TypeError exception
10+
"""
11+
import unittest
12+
from typing import Callable
13+
14+
15+
def is_unique(input_str: str) -> bool:
16+
"""
17+
Determines if input_str has all unique characters.
18+
For all characters in the input_str with n >= 1, where n is the number of characters in input_str,
19+
there must be no duplicate characters.
20+
In the worst case, the run time of this function will be O(n)
21+
Space complexity will be O(n)
22+
Given: Expect:
23+
tacos True
24+
swag True
25+
bobby False
26+
california False
27+
orbit True
28+
e True
29+
"" True
30+
:param input_str: the string we want to check characters of
31+
:return: returns True if input_str has all unique characters, False otherwise
32+
"""
33+
chars_seen = set()
34+
for c in input_str:
35+
if c in chars_seen:
36+
return False
37+
chars_seen.add(c)
38+
return True
39+
40+
41+
def is_unique_no_additional_data_structures(input_str: str) -> bool:
42+
"""
43+
Variant of is_unique. Uses no additional data structures (besides the variables from the iterator)
44+
However, the drawback is that the runtime is O((n*n-1)/2) = O(n^2), where n is the number of characters
45+
in the input_str.
46+
Given: Expect:
47+
tacos True
48+
swag True
49+
bobby False
50+
california False
51+
orbit True
52+
e True
53+
"" True
54+
:param input_str: the string we want to check characters of
55+
:return: returns True if input_str has all unique characters, False otherwise
56+
"""
57+
for i, c in enumerate(input_str):
58+
if c in input_str[i+1:]:
59+
return False
60+
return True
61+
62+
63+
class TestIsUniqueFunction(unittest.TestCase):
64+
def _run_tests(self, f: Callable[[str], None]) -> None:
65+
for case in ["techqueria", "bobby", "california"]:
66+
self.assertFalse(f(case), msg=case)
67+
for case in ["tacos", "swag", "orbit", "e", ""]:
68+
self.assertTrue(f(case), msg=case)
69+
with self.assertRaises(TypeError):
70+
f(8)
71+
72+
def test_is_unique(self):
73+
self._run_tests(is_unique)
74+
75+
def test_is_unique_no_additional_data_structures(self):
76+
self._run_tests(is_unique_no_additional_data_structures)
77+
78+
79+
if __name__ == '__main__':
80+
unittest.main()

0 commit comments

Comments
 (0)