Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 37b34c2

Browse files
sowndappan5MaximSmolskiypre-commit-ci[bot]
authored
perf(strings): optimize anagram signature using frequency counts (#12927)
* fix(strings): use frequency-based signature for anagrams Replaced the sorting-based signature implementation with a frequency-based approach using `collections.Counter`. This ensures that the signature represents both characters and their counts, preventing collisions and better grouping of true anagrams. Examples: - "test" → "e1s1t2" - "finaltest" → "a1e1f1i1l1n1s1t2" - "this is a test" → " 3a1e1h1i2s3t3" Also updated the anagram lookup to use the new frequency-based signatures, making results more accurate and avoiding false positives. * Refactor anagram function return type to list[str] * Update anagrams.py * Update anagrams.py * Update anagrams.py * Update anagrams.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent d16cac6 commit 37b34c2

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

‎strings/anagrams.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,26 @@
66

77

88
def signature(word: str) -> str:
9-
"""Return a word sorted
9+
"""
10+
Return a word's frequency-based signature.
11+
1012
>>> signature("test")
11-
'estt'
13+
'e1s1t2'
1214
>>> signature("this is a test")
13-
' aehiisssttt'
15+
' 3a1e1h1i2s3t3'
1416
>>> signature("finaltest")
15-
'aefilnstt'
17+
'a1e1f1i1l1n1s1t2'
1618
"""
17-
return "".join(sorted(word))
19+
frequencies = collections.Counter(word)
20+
return "".join(
21+
f"{char}{frequency}" for char, frequency in sorted(frequencies.items())
22+
)
1823

1924

2025
def anagram(my_word: str) -> list[str]:
21-
"""Return every anagram of the given word
26+
"""
27+
Return every anagram of the given word from the dictionary.
28+
2229
>>> anagram('test')
2330
['sett', 'stet', 'test']
2431
>>> anagram('this is a test')
@@ -40,5 +47,5 @@ def anagram(my_word: str) -> list[str]:
4047
all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}
4148

4249
with open("anagrams.txt", "w") as file:
43-
file.write("all_anagrams = \n")
50+
file.write("all_anagrams = \n")
4451
file.write(pprint.pformat(all_anagrams))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /