From e19eb712f14c46effb3f9d8a7f50b3e5645d0145 Mon Sep 17 00:00:00 2001 From: anebz Date: Thu, 28 Mar 2019 19:00:52 +0100 Subject: [PATCH] 1.2. check permutation pythonic changes use of counter and *strings for tuples --- .../1.2. check_permutation.py | 47 ++++++++++++++----- 1 file changed, 36 insertions(+), 11 deletions(-) diff --git a/Chapter 1 Arrays and strings/1.2. check_permutation.py b/Chapter 1 Arrays and strings/1.2. check_permutation.py index bb672cb..034591b 100644 --- a/Chapter 1 Arrays and strings/1.2. check_permutation.py +++ b/Chapter 1 Arrays and strings/1.2. check_permutation.py @@ -1,10 +1,12 @@ import unittest +from time import time +from collections import Counter def check_permutation(s1, s2): if len(s1) != len(s2): return False - checker = dict() + checker = dict() for char in s1: ascii_val = ord(char) if ascii_val not in checker: @@ -17,29 +19,52 @@ def check_permutation(s1, s2): if ascii_val not in checker: return False checker[ascii_val] -= 1 - if checker[ascii_val] == 0: - del checker[ascii_val] if checker[ascii_val] < 0: return False - if checker == {}: - return True - else: + return True + +def check_permutation_pythonic(s1, s2): + if len(s1) != len(s2): return False + if len(s1) <= 1: + return True + + counter = Counter() + for char in s1: + counter[char] += 1 + for char in s2: + if counter[char] == 0: + return False + counter[char] -= 1 + return True class Test(unittest.TestCase): - dataT = [('abcd', 'dbca'), ('dfgh', 'dfgh'), ('', '')] + dataT = [('abcd', 'dbca'), ('dfgh', 'dhgf'), ('', '')] dataF = [('aane', 'anee'), ('ab', 'ca'), ('ane', 'aane')] def test(self): # true check for test_string in self.dataT: - s1, s2 = test_string - res = check_permutation(s1, s2) + start = time() + res = check_permutation(*test_string) self.assertTrue(res) + print(f"{time() - start}s") + + start = time() + res = check_permutation_pythonic(*test_string) + self.assertTrue(res) + print(f"{time() - start}s") + # false check for test_string in self.dataF: - s1, s2 = test_string - res = check_permutation(s1, s2) + start = time() + res = check_permutation(*test_string) + self.assertFalse(res) + print(f"{time() - start}s") + + start = time() + res = check_permutation_pythonic(*test_string) + print(f"{time() - start}s") self.assertFalse(res) if __name__ == "__main__":