Skip to content
This repository has been archived by the owner on Nov 19, 2023. It is now read-only.

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
avandekleut committed Sep 28, 2019
0 parents commit a54b644
Show file tree
Hide file tree
Showing 11 changed files with 566,848 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 avandekleut

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# anagram-generator

[![Build Status](https://travis-ci.org/joemccann/dillinger.svg?branch=master)](https://travis-ci.org/joemccann/dillinger)

`anagram-generator` is a minimal python package that lets you generate multi-word anagrams from any corpus. This package is written in pure python and has no dependencies. See `anagram-generator/writeup/writeup.pdf` to learn how it works (**tries** and clever sorting of partially generated anagrams), or read the source code at `anagram-generator/anagram-generator.py`. Example corpuses are in `anagram-generator/corpuses`.

### Installation

Installation is easy using `pip`.

```sh
$ pip install anagramgen
```

### Example
```python
from anagramgen import AnagramGenerator
with open('corpuses/top-5k.txt', 'r') as file:
corpus = [line.strip() for line in file.readlines()]
gen = AnagramGenerator(corpus)
gen.generate("wonderland")
```
returns

```python
[['do', 'lend', 'warn'],
['down', 'land', 're'],
['draw', 'lend', 'on'],
['draw', 'lend', 'no'],
['dawn', 'lend', 'or'],
['end', 'old', 'warn'],
['end', 'lawn', 'rod'],
['end', 'land', 'row'],
['lend', 'nod', 'war'],
['lend', 'nod', 'raw'],
['lawn', 'nod', 'red'],
['land', 'wonder'],
['land', 'own', 'red'],
['land', 'now', 'red'],
['land', 'new', 'rod'],
['a', 'drown', 'lend'],
['and', 'lend', 'row']]
```
1 change: 1 addition & 0 deletions anagramgen/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from anagramgen import AnagramGenerator
73 changes: 73 additions & 0 deletions anagramgen/anagramgen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from random import randrange

class Trie:
def __init__(self):
self.root = {}

def add(self, word):
self.__add(self.root, word[0], word[1:])

def __add(self, node, prefix, suffix):
if prefix not in node:
node[prefix] = {}
if suffix == "":
node[prefix][suffix] = ""
else:
new_prefix = suffix[0]
new_suffix = suffix[1:]
self.__add(node[prefix], new_prefix, new_suffix)

def __contains__(self, word):
word = list(word)
index_string = "['" + "']['".join(word) + "']"
try:
child_nodes = eval("self.root"+index_string)
if '' in child_nodes:
return True
except KeyError:
pass
return False

class AnagramGenerator:
def __init__(self, corpus):
self.t = Trie()
for word in corpus:
word = word.rstrip()
self.t.add(word)

def frequency_dict(self, string):
f = {}
for letter in string:
if letter not in f:
f[letter] = 0
f[letter] += 1
return f

def generate(self, string):
string = string.lower()
for c in string:
if c not in 'abcdefghijklmnopqrstuvwxyz':
string = string.replace(c, "")

anagrams = []
f = self.frequency_dict(string)
self.__generate(anagrams, self.t.root, [], "", f)

return anagrams

def __generate(self, anagrams, node, partial_anagram, current_word, f):
if '' in node: # if we have just finished generating a word
next_partial_anagram = partial_anagram + [current_word]
if all([f[key] == 0 for key in f]): # if there are no more letters
anagrams.append(next_partial_anagram) # then this is a full phrase anagram
else:
self.__generate(anagrams, self.t.root, next_partial_anagram, "", f) # so loop back to the top of the tree with a new word and add a space to the anagram phrase we are building

for prefix in f:
if f[prefix] > 0:
if prefix in node:
new_word = current_word+prefix
if len(partial_anagram) == 0 or new_word >= partial_anagram[-1][:len(new_word)]:
f[prefix] -= 1 # since f is shared between function calls we need to subtract from it
self.__generate(anagrams, node[prefix], partial_anagram, current_word+prefix, f)
f[prefix] += 1 # then add back
Loading

0 comments on commit a54b644

Please sign in to comment.