Advertisement
chaosagent

Untitled

Dec 9th, 2015
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. grid = \
  2. [['E', 'E', 'C', 'A'],
  3. ['A', 'L', 'E', 'P'],
  4. ['H', 'N', 'B', 'O'],
  5. ['Q', 'T', 'T', 'Y']]
  6.  
  7. def traverse_grid(x, y, s, i, used):
  8. if i >= len(s):
  9. return True
  10. result = False
  11. for (nx, ny) in filter(lambda coords: 0 <= coords[0] < 4 and 0 <= coords[1] < 4 and coords != (x, y) and grid[coords[0]][coords[1]] == s[i] and (coords[0] * 4 + coords[1]) not in used, reduce(lambda a, b: a + b, [[(x + m, y + n) for m in xrange(-1, 2)] for n in xrange(-1, 2)])):
  12. result = result or traverse_grid(nx, ny, s, i + 1, dict(used, **{nx * 4 + ny: True}))
  13. if result: break
  14. return result
  15.  
  16. seen = {}
  17. count = 0
  18. for word in open('words.txt', 'r'):
  19. word = word.strip().upper()
  20. if word in seen:
  21. continue
  22. seen[word] = True
  23. if filter(lambda x: traverse_grid(x / 4, x % 4, word, 0, {}), range(16)):
  24. count += 1
  25. print count, word
  26.  
  27. exit(0)
  28.  
  29. class Node:
  30. letter = ''
  31. count = 0
  32. nexts = {}
  33.  
  34. def __init__(self, letter=''):
  35. self.letter = letter
  36. root = Node()
  37. def build_trie(prevnode, x, y, used):
  38. if grid[x][y] not in prevnode.nexts:
  39. prevnode.nexts[grid[x][y]] = Node(grid[x][y])
  40. currnode = prevnode.nexts[grid[x][y]]
  41. for (nx, ny) in filter(lambda coords: 0 <= coords[0] < 4 and 0 <= coords[1] < 4 and coords != (x, y) and (coords[0] * 4 + coords[1]) not in used, reduce(lambda a, b: a + b, [[(x + i, y + j) for i in xrange(-1, 2)] for j in xrange(-1, 2)])):
  42. build_trie(currnode, nx, ny, dict(used, **{nx * 4 + ny: True}))
  43. for i in xrange(16):
  44. build_trie(root, i / 4, i % 4, {i * 4 + (i % 4): True})
  45. print i
  46. def is_in_trie(currnode, s, i):
  47. while True:
  48. if s[i] not in currnode.nexts:
  49. return False
  50. currnode = currnode.nexts[s[i]]
  51. i += 1
  52. return True
  53. count = 0
  54. for word in open('words.txt', 'r'):
  55. word = word.strip().upper()
  56. if is_in_trie(root, word, 0):
  57. count += 1
  58. print count, word
  59. exit(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement