def main(): words_dictionary = Trie() file_name = sys.argv[1] lowercase_letters = string.ascii_lowercase try: with open(file_name, 'r') as file_handle: for word in file_handle: words_dictionary.insert_word(word.rstrip()) except FileNotFoundError: print("The file name provided doesn't exist. Try again!") sys.exit() word_search_game = WordSearch(words_dictionary) while True: cmd = int(input("Enter 1 to play else any other digit to exit! : ")) if cmd == 1: num_rows = int( input("Please enter number of rows for the grid : ")) num_cols = int( input("Please enter number of columns for the grid : ")) start = time.time() grid = [[ random.choice(lowercase_letters) for i in range(num_cols) ] for j in range(num_rows)] print('\n') for row in grid: print(row) print(word_search_game.search_valid_words(grid)) print("\nTotal execution time : ", time.time() - start, "\n") else: sys.exit()
def test_read_valid_file(self): expected_puzzle = [ 'GXWRVZNZXVAXBXN', 'LOOFIDSEOJAATMW', 'CFKDIZWOKRLMGMN', 'UOVXRNPTUCGDZIG', 'OJEUZMDMIMIGVLX', 'AWOCYQWQHXPHJLD', 'BEJNKRFDPKNYCFT', 'EGWFTZKRNFEFMWZ', 'WPTXSMWLNEYCBFD', 'AGZZZDJWMKLJJYN', 'BJTUPFCLWSVXREE', 'QFINRMZMYDNNLKB', 'HYLLWPTYNLCPKCH', 'TCAUNJVTWOQKXUF', 'JFPVOPYTFYIPAPB' ] expected_words = ['CHICKEN', 'COW', 'PIG'] ws = WordSearch('data/farm.pzl') ws.read() self.assertEqual(expected_words, ws.words_to_search) self.assertEqual(expected_puzzle, ws.puzzle)
class TestErrors(ExtendedTestCase): """Test the erronous operations WordSearch""" def setUp(self): """This runs before the test cases are executed""" self.word_search = WordSearch() def tearDown(self): """This runs after the test cases are executed""" self.word_search = None def test_file_not_found(self): """""" no_file = "puzzle1.pzlssss" error = "file {} not found in puzzles directory".format(no_file) self.word_search.set_puzzle_file(no_file) self.assertRaisesWithMessage(error, self.word_search.run_search) def test_file_with_one_letter(self): """""" no_file = "puzzle_w_one_letter.pzl" error = "A should be more than 2 characters" self.word_search.set_puzzle_file(no_file) self.assertRaisesWithMessage(error, self.word_search.run_search) def test_file_invalid_search(self): """""" no_file = "puzzle_w_invalid_search.pzl" error = "@ is not a valid alphabet" self.word_search.set_puzzle_file(no_file) self.assertRaisesWithMessage(error, self.word_search.run_search) def test_file_invalid_crosswords(self): """""" no_file = "puzzle_w_invalid_crosswords.pzl" error = "CI@N is not a valid alphabet" self.word_search.set_puzzle_file(no_file) self.assertRaisesWithMessage(error, self.word_search.run_search) def test_file_uneven_puzzle(self): """""" no_file = "puzzle_uneven_matrix.pzl" error = "Puzzle file must have equal dimension (X,X)" self.word_search.set_puzzle_file(no_file) self.assertRaisesWithMessage(error, self.word_search.run_search)
def test_write_results_failure(self, mock_logger): expected_results = OrderedDict() expected_results['DIAMOND'] = [(7, 1), (1, 1)] ws = WordSearch('data/farm.pzl') ws.read() ws.solve() ws.write()
def showPuzzle(): global gridDict, activeSquares grid_size = 15 words = ("OXYGEN,PARTICULATES,POLLUTION,NITROGEN") #words=("ZZZZZZ") w = WordSearch(words, grid_size, grid_size) gridDict = {} activeSquares = set([ tuple2id((r + 1, c + 1)) for r in range(grid_size) for c in range(grid_size) if w.nakedSquare[r][c] != '*' ]) wordList = list(map(LI, words.split(","))) for p in wordList: p.style = {"text-align": "left"} waffle = DIV(SPAN("Can you find these words in the box?") + UL(wordList) + SPAN("Click on the words you find"), Class="txt") return DIV(html.TABLE( TR(TD(DIV(make_grid(w, grid_size), Class="border")) + TD(waffle)), style={ "backgroundColor": "#99f9ea", "margin": "auto" }), style={"backgroundColor": "#99f9ea"})
def test_word_correlation(self): """ the dataset is made in such a way that the elements with 'DIKU' should have a greater average """ DIKU = WordSearch.word_correlation(self.alist, 'DIKU') #the average of the whole list should be greater than average of the elements containing 'DIKU' self.assertGreater(statistical.get_average(self.alist, 'reactions'), DIKU)
def test_search_word(self): print(self.alist) """ the word humtek appears in all posts, so this method should be returning 7 """ occurences = WordSearch.search_word(self.alist, 'Humtek') self.assertEqual(occurences, 7)
def makeWordSearch(): # words = a variable with all the words, which are all separated by a comma. # Note : the variable which contains all words mustn't be called words. words = ("Hello,Blah,Superhero,XXXXX") x = 10 y = 10 # x & y indicate the size of the word search. # Note: When you take a look at our code, you will see 'grid' (a list). #Grid is a a list which contains lists(columns) which contain letters (strings). w = WordSearch(words, x, y)
def test_write_results_valid(self): expected_results = [ 'CHICKEN Not Found \n', 'COW (4, 6) (2, 6) \n', 'PIG (11, 6) (11, 4) \n' ] ws = WordSearch('data/farm.pzl') ws.read() ws.solve() ws.write() with open(ws.file_name + '.out', 'rw') as f: data = f.readlines() self.assertEquals(data, expected_results)
def test_word_search(self): words_dictionary = Trie() words = ["naruto", "naru", "leemo", "hokage", "leaf", "sakura", \ "saskent", "kiba", "lee", "noji", "leen"] for word in words: words_dictionary.insert_word(word) word_search_game = WordSearch(words_dictionary) grid = [['n', 'j', 'r', 'u'], ['o', 'a', 'i', 't'], ['l', 'e', 'o', 'p'], ['e', 'n', 'm', 'q']] valid_words = set(["noji", "naru", "naruto", "lee", "leen", "leemo"]) ret_words = word_search_game.search_valid_words(grid) for word in ret_words: if word in valid_words: valid_words.remove(word) else: valid_words.add(word) self.assertEqual(len(valid_words), 0)
def test_solve_vertical_valid(self): expected_results = OrderedDict() expected_results['HEART'] = [(5, 7), (5, 3)] ws = WordSearch('data/suits.pzl') ws.read() for word in ws.words_to_search: word_reversed = word[::-1] ws._solve_vertical(word, word_reversed) self.assertEqual(ws.results, expected_results)
def test_solve_horizontal_valid(self): expected_results = OrderedDict() expected_results['DIAMOND'] = [(7, 1), (1, 1)] ws = WordSearch('data/suits.pzl') ws.read() for word in ws.words_to_search: word_reversed = word[::-1] ws._solve_horizontal(word, word_reversed) self.assertEqual(ws.results, expected_results)
def test_basic_functionality(self): grid = "catsdgdrjk" \ "wordtsodtk" \ "jsdkjwgrdt" \ "jsdkjwdrdt" \ "jsdkjwtrdt" \ "aajgyhksdg" \ "jsdhellodt" \ "jsdkjwtthi" \ "ngdkjwtrdt" \ "jsstuffrdt" words_to_find = ["cats", "dog", "hello", "thing", "dynamic" ] # 'thing' is there, but looped over 2 lines ws = WordSearch(grid) self.assertEquals(standard_search(ws, words_to_find), correct_output(["cats", "dog", "hello"]))
def speed_test_sample(grid_size, max_word_length, no_of_words): letters = string.ascii_lowercase grid = ''.join(random.choice(letters) for _ in range(grid_size)) words_to_find = [(''.join( random.choice(letters) for _ in range(random.randint(1, max_word_length)))) for _ in range(no_of_words)] ws = WordSearch(grid) start = datetime.now() standard_search(ws, words_to_find) single_time = datetime.now() - start start = datetime.now() multi_processing_search(ws, words_to_find) multi_time = datetime.now() - start return multi_time, single_time
def test_search(self): ws = WordSearch() self.assertFalse(ws.exist([[]], "AB")) chars = [['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']] self.assertTrue(ws.exist(chars, "ABCCED")) self.assertTrue(ws.exist(chars, "SEE")) self.assertFalse(ws.exist(chars, "ABCB"))
def test_solve_valid_data(self): expected_results = OrderedDict() expected_results['DICTIONARY'] = [(1, 5), (1, 14)] expected_results['INTEGER'] = 'Not Found' expected_results['LIST'] = 'Not Found' expected_results['PIP'] = [(6, 10), (8, 10)] expected_results['PYTHON'] = [(15, 14), (10, 14)] expected_results['STRING'] = 'Not Found' expected_results['TUPLE'] = [(8, 6), (8, 2)] ws = WordSearch('data/python.pzl') ws.read() ws.solve() self.assertEquals(ws.results, expected_results)
def _reshuffle(self): """ Command for the "Reshuffle" button. Uses the existing words and creates a new word search board with the words in new locations. """ self._export_button.configure(text='Export', state=tk.NORMAL) if self._solution_shown: self._solution_shown = not self._solution_shown self._word_search = WordSearch(self._size, self._words) self._pushed.clear() for i in range(self._size): for j in range(self._size): self._buttons[i][j].configure( text=self._word_search.board[i][j], bg='SystemButtonFace', state=tk.NORMAL) for label in self._labels.values(): label.configure(bg='SystemButtonFace')
from WordSearch import WordSearch alphabet = "ETAOINSRHDLUCMFYWGPBVKXQJZ"[::-1].lower() clusters = ['bl', 'br', 'ch', 'cl', 'cr', 'dr', 'fl', 'fr', 'gl', 'gr', 'pl', 'pr', 'sc', 'sh', 'sk', 'sl', 'sm', 'sn', 'sp', 'st', 'sw', 'th', 'tr', 'tw', 'wh', 'wr', 'sch', 'scr', 'shr', 'sph', 'spl', 'spr', 'squ', 'str', 'thr'] cluster_1 = ['b','c','d','f','g','p','s','t','w'] def unique(seq): seen = set() seen_add = seen.add return [ x for x in seq if not (x in seen or seen_add(x))] def pos(seq, n): return [x for x in seq if x[0] >= 0 and x[1] >= 0 and x[0] < n and x[1] < n] n = 10 board = WordSearch(n,False) board.fill(n) board.print_board() wordlist = [i.upper() for i in board.get_wordlist()] for i in wordlist: print i, print '\n' #board length bl = len(board.board) # length of wordlist wl = len(wordlist) #first letters fl = [] #first letter locations (row,col)
def setUp(self): search = WordSearch('animals.pzl') search.start_search()
def setUp(self): search = WordSearch('lostDuck.pzl') search.start_search()
def setUp(self): search = WordSearch('search.pzl') search.start_search()
def setUp(self): """This runs before the test cases are executed""" self.word_search = WordSearch()
class TestLogics(ExtendedTestCase): """Test the logical operations WordSearch""" def setUp(self): """This runs before the test cases are executed""" self.word_search = WordSearch() def tearDown(self): """This runs after the test cases are executed""" self.word_search = None def test_valid_input_output(self): """""" _file = "puzzle1.pzl" self.word_search.set_puzzle_file(_file) self.word_search.run_search() with open(self.word_search.get_output_path()) as f: lines = f.read() pprint.pprint(lines) self.assertMultiLineEqual( "CAT (1, 1)(1, 3)\nDOG (2, 2)(4, 2)\nCOW (2, 4)(4, 4)\n", lines) def test_valid_input_with_reverse(self): """""" _file = "suits.pzl" self.word_search.set_puzzle_file(_file) self.word_search.run_search() with open(self.word_search.get_output_path()) as f: lines = f.read() pprint.pprint(lines) self.assertMultiLineEqual( "DIAMOND (7, 1)(1, 1)\nHEART (7, 5)(5, 3)\n", lines) def test_valid_with_newlines(self): """""" _file = "puzzle_far_inputs.pzl" self.word_search.set_puzzle_file(_file) self.word_search.run_search() with open(self.word_search.get_output_path()) as f: lines = f.read() pprint.pprint(lines) self.assertMultiLineEqual( "CAT (1, 1)(1, 3)\nDOG (2, 2)(4, 2)\nCOW (2, 4)(4, 4)\n", lines) def test_valid_with_blank_each(self): """""" _file = "puzzle_has_blank_each_inputs.pzl" self.word_search.set_puzzle_file(_file) self.word_search.run_search() with open(self.word_search.get_output_path()) as f: lines = f.read() pprint.pprint(lines) self.assertMultiLineEqual( "CAT (1, 1)(1, 3)\nDOG (2, 2)(4, 2)\nCOW (2, 4)(4, 4)\n", lines) def test_valid_with_lost_word(self): """""" _file = "lostDuck.pzl" self.word_search.set_puzzle_file(_file) self.word_search.run_search() with open(self.word_search.get_output_path()) as f: lines = f.read() pprint.pprint(lines) self.assertMultiLineEqual( "CAT (1, 1)(1, 3)\nDOG (2, 2)(4, 2)\nDUCK not found\n", lines)
def test_word_counter(self): most_common = WordSearch.word_counter(self.alist) self.assertEqual(most_common[0][0], 'Humtek') self.assertIsNot(most_common[1], 'is')
from WordSearch import WordSearch board = WordSearch(5, True) board.fill(10) board.print_board() print board.get_wordlist()
from WordSearch import WordSearch import sys if __name__ == '__main__': word_search = WordSearch() word_search.read_file(sys.argv[1]) word_search.solve_grid()
* Ingeniero Fernando Solis * * Version: 1.0 */ """ import string import random from WordSearch import WordSearch matriz = [] dimension = input("Ingrese la dimension deseada para la matriz\n") x = int(dimension) for i in range(x): matriz.append([0] * x) for c in range(x): for j in range(x): matriz[c][j] = random.choice(string.ascii_lowercase) for i in range(x): print(matriz[i]) Matrix = WordSearch(x) palabra = input("Ingrese la palabra a buscar\n") if Matrix.searchWord(matriz, palabra): print("Acerto") Matrix.printM() else: print("Fallo")
import string, random def random_grid(LEN): a = [[0 for x in range(LEN)] for y in range(LEN)] for i in range(LEN): for j in range(LEN): a[i][j] = random.choice(string.ascii_lowercase) return a grid = random_grid(ROW_LENGTH) # Start program ws = WordSearch(grid) # Benchmarking import time t = time.time() # Start processing for word in words_to_find: # t1 = time.time() if ws.is_present(word): print("found {}".format(word)) # print(word, time.time() - t1) print("Took ", time.time() - t, " seconds to find all words without multiprocessing. ")
def test_call_solve_before_read(self): ws = WordSearch('data/farm.pzl') self.assertRaisesWithMessage('No puzzle has been loaded.', ws.solve)
def test_call_write_before_solve(self): ws = WordSearch('data/farm.pzl') self.assertRaisesWithMessage('There are no results to write.', ws.write)
def test_read_empty_file(self, mock_logger): ws = WordSearch('data/empty.pzl') self.assertRaises(WordSearchException, ws.read) self.assertEquals(mock_logger.error.call_count, 1) mock_logger.error.assert_called_with( 'Error reading file: Puzzle file is empty: data/empty.pzl')
def test_read_missing_file(self): ws = WordSearch('data/no_such_file.pzl') self.assertRaises(WordSearchException, ws.read)