Created
August 13, 2016 06:58
-
-
Save cyang-el/50dbe7a7ee117494030b088cf38027c5 to your computer and use it in GitHub Desktop.
group anagrams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def check_anagram_with_char_checkoff(s1, s2): | |
if len(s1) != len(s2): | |
return False | |
c1 = [False] * len(s1) | |
c2 = [False] * len(s2) | |
for i in range(len(s1)): | |
for j in range(len(s2)): | |
if s1[i] == s2[j]: | |
if not c2[j]: | |
c1[i] = True | |
c2[j] = True | |
break | |
return all(i for i in c1) and all(j for j in c2) | |
def test_check_anagram_with_char_checkoff(): | |
a = "aaa" | |
b = "aaaaa" | |
assert not check_anagram_with_char_checkoff(a, b) | |
a = "python" | |
b = "typhon" | |
assert check_anagram_with_char_checkoff(a, b) | |
a = "aaa" | |
b = "aaa" | |
assert check_anagram_with_char_checkoff(a, b) | |
def group_anagrams(args): | |
_r = [] | |
checked = [False] * len(args) | |
for i in range(len(args)): | |
_g = [] | |
for j in range(len(args)): | |
if not (checked[i] and checked[j]): | |
if check_anagram_with_char_checkoff(args[i], args[j]): | |
checked[j] = True | |
_g.append(args[j]) | |
if not checked[i]: | |
checked[i] = True | |
_g.append(args[i]) | |
if len(_g) > 0: | |
_r.append(_g) | |
return _r | |
def test_group_anagrams(): | |
a= ["aa", "aa", "python", "typhon", "aaa", "e", "thonpy"] | |
assert group_anagrams(a) == [['aa', 'aa'], ['python', 'typhon', 'thonpy'], ['aaa'], ['e']] | |
test_check_anagram_with_char_checkoff() | |
test_group_anagrams() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment