This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
In [1]:
def unique_chars(string):
return len(set(string)) == len(string)
We'll keep a hash map (set) to keep track of unique characters we encounter.
Steps:
Notes:
Complexity:
In [2]:
def unique_chars_hash(string):
chars_set = set()
for char in string:
if char in chars_set:
return False
else:
chars_set.add(char)
return True
Assume we cannot use additional data structures, which will eliminate the fast lookup O(1) time provided by our hash map.
Algorithm Complexity:
In [3]:
def unique_chars_inplace(string):
for char in string:
if string.count(char) > 1:
return False
return True
In [4]:
%%writefile test_unique_chars.py
from nose.tools import assert_equal
class TestUniqueChars(object):
def test_unique_chars(self, func):
assert_equal(func(''), True)
assert_equal(func('foo'), False)
assert_equal(func('bar'), True)
print('Success: test_unique_chars')
def main():
test = TestUniqueChars()
test.test_unique_chars(unique_chars)
try:
test.test_unique_chars(unique_chars_hash)
test.test_unique_chars(unique_chars_inplace)
except NameError:
# Alternate solutions are only defined
# in the solutions file
pass
if __name__ == '__main__':
main()
In [5]:
%run -i test_unique_chars.py