Skip to content

Commit c682bb5

Browse files
committed
use collections.Counter for histogram
1 parent d6293a2 commit c682bb5

File tree

1 file changed

+5
-16
lines changed

1 file changed

+5
-16
lines changed

Python/chapter01/1.2 - Check Perm/miguel_1.2_sol.py

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
Given two strings, write a method to decide if one is a permutation of the other.
55
"""
66
import unittest
7+
import collections
78
from typing import Callable
89

910

@@ -27,30 +28,18 @@ def check_permutation(s1: str, s2: str) -> bool:
2728
:param s2: string of size m
2829
:return: True if s1 is a permutation of s2, False otherwise
2930
"""
30-
# permutations must be of equal length, one-to-one
31-
if len(s1) != len(s2):
32-
return False
33-
freqs_s1 = {}
3431
# build histogram of seen characters in s1
3532
# using histogram because string could have repeated characters
36-
for c in s1:
37-
if c not in freqs_s1:
38-
freqs_s1[c] = 1
39-
continue
40-
freqs_s1[c] += 1
33+
freqs_s1 = collections.Counter(s1)
4134

42-
freqs_s2 = {}
35+
# check if s2 characters exist in s1
4336
for c in s2:
4437
# if character in s2 not in s1, then this is not a permutation
4538
if c not in freqs_s1:
4639
return False
47-
# otherwise, populate as normal
48-
if c not in freqs_s2:
49-
freqs_s2[c] = 1
50-
continue
51-
freqs_s2[c] += 1
5240

53-
# compare frequences of characters for s1 and s2
41+
freqs_s2 = collections.Counter(s2)
42+
# compare frequencies of characters for s1 and s2
5443
for key, val in freqs_s1.items():
5544
if val != freqs_s2[key]:
5645
# character counts between s1 and s2 don't match

0 commit comments

Comments
 (0)