This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
Permutations contain the same strings but in different orders. This approach could be slow for large strings due to sorting.
Complexity:
In [1]:
def permutations(str1, str2):
return sorted(str1) == sorted(str2)
We'll keep a hash map (dict) to keep track of characters we encounter.
Steps:
Notes:
Complexity:
In [2]:
from collections import defaultdict
def unique_counts(string):
dict_chars = defaultdict(int)
for char in string:
dict_chars[char] += 1
return dict_chars
def permutations_alt(str1, str2):
if len(str1) != len(str2):
return False
unique_counts1 = unique_counts(str1)
unique_counts2 = unique_counts(str2)
return unique_counts1 == unique_counts2
In [3]:
%%writefile test_permutation_solution.py
from nose.tools import assert_equal
class TestPermutation(object):
def test_permutation(self, func):
assert_equal(func('', 'foo'), False)
assert_equal(func('Nib', 'bin'), False)
assert_equal(func('act', 'cat'), True)
assert_equal(func('a ct', 'ca t'), True)
print('Success: test_permutation')
def main():
test = TestPermutation()
test.test_permutation(permutations)
try:
test.test_permutation(permutations_alt)
except NameError:
# Alternate solutions are only defined
# in the solutions file
pass
if __name__ == '__main__':
main()
In [4]:
run -i test_permutation_solution.py