Skip to content

edited strings/anagram.py #5770

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Nov 8, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 32 additions & 23 deletions strings/anagrams.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,44 @@
from __future__ import annotations

import collections
import os
import pprint
import time
from pathlib import Path


def signature(word: str) -> str:
"""Return a word sorted
>>> signature("test")
'estt'
>>> signature("this is a test")
' aehiisssttt'
>>> signature("finaltest")
'aefilnstt'
"""
return "".join(sorted(word))

start_time = time.time()
print("creating word list...")
path = os.path.split(os.path.realpath(__file__))
with open(path[0] + "/words.txt") as f:
word_list = sorted(list({word.strip().lower() for word in f}))

def anagram(my_word: str) -> list[str]:
"""Return every anagram of the given word
>>> anagram('test')
['sett', 'stet', 'test']
>>> anagram('this is a test')
[]
>>> anagram('final')
['final']
"""
return word_bysig[signature(my_word)]

def signature(word):
return "".join(sorted(word))

data: str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8")
word_list = sorted(list({word.strip().lower() for word in data.split("\n")}))

word_bysig = collections.defaultdict(list)
for word in word_list:
word_bysig[signature(word)].append(word)

if __name__ == "__main__":
all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}

def anagram(my_word):
return word_bysig[signature(my_word)]


print("finding anagrams...")
all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}

print("writing anagrams to file...")
with open("anagrams.txt", "w") as file:
file.write("all_anagrams = ")
file.write(pprint.pformat(all_anagrams))

total_time = round(time.time() - start_time, 2)
print(("Done [", total_time, "seconds ]"))
with open("anagrams.txt", "w") as file:
file.write("all_anagrams = \n ")
file.write(pprint.pformat(all_anagrams))
Loading