Guest User

Untitled

a guest
May 23rd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import functools
  2. import sys
  3. from collections import namedtuple
  4.  
  5. Memo = namedtuple('Memo', ['word', 'neighbors', 'visited'])
  6.  
  7. #sys.setrecursionlimit(10 * 1000 * 1)
  8. #@functools.lru_cache()
  9. def find_words(input, dictionary_set):
  10. """
  11. Find all "simple paths" in an undirected graph
  12. """
  13.  
  14. for row in range(len(input)):
  15. for col in range(len(input[0])):
  16. stack = [Memo('', [(row, col)], set())]
  17. while stack:
  18. uber_word, uber_neighbors, uber_visited = stack.pop()
  19. while uber_neighbors:
  20. (x, y) = uber_neighbors.pop()
  21. sub_visited = uber_visited.copy()
  22. word = uber_word
  23.  
  24. if (x, y) not in sub_visited:
  25. sub_visited.add((x, y))
  26.  
  27. word += input[x][y]
  28. check_word(word, dictionary_set)
  29.  
  30. sub_neighbors = find_neighbors(x, y, len(input), len(input[0]), sub_visited)
  31. stack.append(Memo(word, sub_neighbors, sub_visited))
  32.  
  33. if len(word) > 9:
  34. raise Exception('word can never be longer than 9 characters')
  35.  
  36. if not(sub_neighbors):
  37. print('no_neighbors', word)
  38.  
  39. def check_word(word, dictionary_set):
  40. print('checking', word)
  41. if word in dictionary_set:
  42. print(word)
  43.  
  44. def find_neighbors(r, c, x_limit, y_limit, visited):
  45. result = set([
  46. (r-1, c-1), #W
  47. (r-1, c), #I
  48. (r+1, c), #A
  49. (r, c-1), #S
  50. (r, c+1), #K
  51. (r+1, c-1), #E
  52. (r+1, c+1), #X
  53. (r-1, c+1) #N
  54. ]) - visited
  55.  
  56. return [elem for elem in result if 0 <= elem[0] < x_limit and 0 <= elem[1] < y_limit]
  57.  
  58.  
  59.  
  60. '''
  61. wse
  62. ita
  63. nkx
  64.  
  65. wt...
  66. ws...
  67. '''
  68. input = [['w', 's', 'e'], ['i', 't', 'a'], ['n', 'k', 'x']]
  69. dictionary_set = set(['sea', 'tin', 'win', 'wink', 'set', 'seat', 'kite', 'tax'])
  70. find_words(input, dictionary_set)
Add Comment
Please, Sign In to add comment