Skip to content

Instantly share code, notes, and snippets.

@azone
Created October 29, 2012 05:43
Show Gist options
  • Save azone/3971788 to your computer and use it in GitHub Desktop.
Save azone/3971788 to your computer and use it in GitHub Desktop.
This is a interactive cli tool to solve the Letterpress game by Yozone Wang
#/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys
import time
import math
GROUP = 4
COUNT = int(math.ceil(26.0 / GROUP))
PRIME_TUPLE = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31)
def process_word(word):
result = []
for i in xrange(GROUP):
result.append(1)
for letter in word:
c = ord(letter) - 97
try:
result[c / COUNT] *= PRIME_TUPLE[c % COUNT]
except IndexError as e:
return False
return result
def is_match(word_prime, input_prime):
for i in xrange(GROUP):
if input_prime[i] % word_prime[i] != 0:
return False
return True
word_list = []
def read_words(dir):
print('Reading words list...')
for filename in os.listdir(dir):
if filename.endswith('.txt'):
f = open(filename,'r')
for word in f.xreadlines():
word = word.strip()
word_prime = process_word(word)
if word_prime != False:
word_list.append({'word':word, 'prime': process_word(word)})
f.close()
def main():
print("I'm ready!")
while True:
try:
input_letters = raw_input('input the letters> ')
startTime = time.time()
input_letters = input_letters.strip().lower()
input_prime = process_word(input_letters)
matched_words = []
for word in word_list:
if is_match(word['prime'], input_prime):
matched_words.append(word['word'])
matched_words = sorted(matched_words, key=lambda s: len(s), reverse=True)
print("process in %.2fms" % ((time.time() - startTime) * 1000, ))
for word in matched_words[:50]:
print(word)
except KeyboardInterrupt as e:
break
if __name__ == '__main__':
read_words('.')
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment