1.2. check permutation pythonic changes
use of counter and *strings for tuples
This commit is contained in:
parent
78c1fd4eef
commit
e19eb712f1
|
|
@ -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:
|
||||
|
||||
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__":
|
||||
|
|
|
|||
Loading…
Reference in New Issue