Thomas
0
Q:

word search puzzle python

An improved (shorter, more efficient) version of the above:
 
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
puzzle='''F Y Y H N R D
R L J C I N U
A A W A A H R
N T K L P N E
C I L F S A P
E O G O T P N
H P O L A N D
'''
clues = ['ITALY', 'HOLLAND', 'POLAND', 'SPAIN',
            'FRANCE', 'JAPAN', 'TOGO', 'PERU']
   
puzzle = puzzle.replace(' ','')            
length = puzzle.index('\n')+1
#Make a list of tuples containing each letter and its row and column
letters = [(letter, divmod(index, length))
            for  index, letter in enumerate (puzzle)]
#Reorder the list to represent each reading direction,
#and add them all to a dictionary
lines = {}
offsets = {'down':0, 'right down':-1, 'left down':1}
for direction, offset in offsets.items():
    lines[direction] = []
    for i in range(length):
        for j in range(i, len(letters), length + offset):
            lines[direction].append(letters[j])
        lines[direction].append('\n')
lines['left']  = letters
lines['right'] = [i for i in reversed(letters)]
lines['up'] = [i for i in reversed(lines['down'])]
lines['left up'] = [i for i in reversed(lines['right down'])]
lines['right up'] = [i for i in reversed(lines['left down'])]
#Make strings from the letters, find the words in them and retrieve
#their original locations
for direction, tup in lines.items():
    string = ''.join([i[0] for i in tup])
    for word in clues:
        if word in string:
            location = tup[string.index(word)][1]
            print word, 'row', location[0]+1, 'column', location[1]+1, direction
0

New to Communities?

Join the community