|
| 1 | +""" |
| 2 | +Python version 3.7.0 |
| 3 | +1.2 - Check Permutation |
| 4 | +Given two strings, write a method to decide if one is a permutation of the other. |
| 5 | +""" |
| 6 | +import unittest |
| 7 | +import collections |
| 8 | +from typing import Callable |
| 9 | + |
| 10 | + |
| 11 | +def check_permutation(s1: str, s2: str) -> bool: |
| 12 | + """ |
| 13 | + Determines if a s1 is a permutation of s2. |
| 14 | + s1 is a permutation of s2 if the characters from s1 map to |
| 15 | + the same characters in s2 in a one-to-one correspondence AND s1 and s2 are of the same length. |
| 16 | + Runtime: O(n + m), where n is the length of s1 and m is the length of s2. |
| 17 | + Given: Expect: |
| 18 | + "tacos", "costa" True |
| 19 | + "tacoos", "costa" False |
| 20 | + "swag", "hello" False |
| 21 | + "hi", "hello" False |
| 22 | + "hola", "loha" True |
| 23 | + "p3nding", "dingp3n" True |
| 24 | + "", "test" False |
| 25 | + "", "" True |
| 26 | + "test2", "" False |
| 27 | + :param s1: string of size n |
| 28 | + :param s2: string of size m |
| 29 | + :return: True if s1 is a permutation of s2, False otherwise |
| 30 | + """ |
| 31 | + # precondition for a permutation, must be same length |
| 32 | + if len(s1) != len(s2): |
| 33 | + return False |
| 34 | + # build histogram of seen characters in s1 and s2 |
| 35 | + # using histogram because string could have repeated characters |
| 36 | + freqs_s1 = collections.Counter(s1) |
| 37 | + freqs_s2 = collections.Counter(s2) |
| 38 | + # compare frequencies of characters for s1 and s2 |
| 39 | + for key, val in freqs_s1.items(): |
| 40 | + if val != freqs_s2[key]: |
| 41 | + # character counts between s1 and s2 don't match |
| 42 | + return False |
| 43 | + return True |
| 44 | + |
| 45 | + |
| 46 | +class TestCheckPermutationFunction(unittest.TestCase): |
| 47 | + def _run_tests(self, f: Callable[[str, str], None]) -> None: |
| 48 | + false_cases = [ |
| 49 | + ("tacoos", "costa"), ("swag", "hello"), ("hi", "hello"), ("tacooos", "costaaa"), |
| 50 | + ("", "test"), ("test2", "") |
| 51 | + ] |
| 52 | + for case in false_cases: |
| 53 | + self.assertFalse(f(case[0], case[1]), msg=case) |
| 54 | + |
| 55 | + true_cases = [ |
| 56 | + ("tacos", "costa"), ("hola", "loha"), ("p3nding", "dingp3n"), ("same", "same"), ("", "") |
| 57 | + ] |
| 58 | + for case in true_cases: |
| 59 | + self.assertTrue(f(case[0], case[1]), msg=case) |
| 60 | + with self.assertRaises(TypeError): |
| 61 | + f(8) |
| 62 | + |
| 63 | + def test_check_permutation(self): |
| 64 | + self._run_tests(check_permutation) |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == '__main__': |
| 68 | + unittest.main() |
0 commit comments