MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / WordSearch

Class WordSearch

other/word_search.py:20–344  ·  view source on GitHub ↗

>>> ws = WordSearch(WORDS, WIDTH, HEIGHT) >>> ws.board # doctest: +ELLIPSIS [[None, ..., None], ..., [None, ..., None]] >>> ws.generate_board()

Source from the content-addressed store, hash-verified

18
19
20class WordSearch:
21 """
22 >>> ws = WordSearch(WORDS, WIDTH, HEIGHT)
23 >>> ws.board # doctest: +ELLIPSIS
24 [[None, ..., None], ..., [None, ..., None]]
25 >>> ws.generate_board()
26 """
27
28 def __init__(self, words: list[str], width: int, height: int) -> None:
29 self.words = words
30 self.width = width
31 self.height = height
32
33 # Board matrix holding each letter
34 self.board: list[list[str | None]] = [[None] * width for _ in range(height)]
35
36 def insert_north(self, word: str, rows: list[int], cols: list[int]) -> None:
37 """
38 >>> ws = WordSearch(WORDS, 3, 3)
39 >>> ws.insert_north("cat", [2], [2])
40 >>> ws.board # doctest: +NORMALIZE_WHITESPACE
41 [[None, None, 't'],
42 [None, None, 'a'],
43 [None, None, 'c']]
44 >>> ws.insert_north("at", [0, 1, 2], [2, 1])
45 >>> ws.board # doctest: +NORMALIZE_WHITESPACE
46 [[None, 't', 't'],
47 [None, 'a', 'a'],
48 [None, None, 'c']]
49 """
50 word_length = len(word)
51 # Attempt to insert the word into each row and when successful, exit
52 for row in rows:
53 # Check if there is space above the row to fit in the word
54 if word_length > row + 1:
55 continue
56
57 # Attempt to insert the word into each column
58 for col in cols:
59 # Only check to be made here is if there are existing letters
60 # above the column that will be overwritten
61 letters_above = [self.board[row - i][col] for i in range(word_length)]
62 if all(letter is None for letter in letters_above):
63 # Successful, insert the word north
64 for i in range(word_length):
65 self.board[row - i][col] = word[i]
66 return
67
68 def insert_northeast(self, word: str, rows: list[int], cols: list[int]) -> None:
69 """
70 >>> ws = WordSearch(WORDS, 3, 3)
71 >>> ws.insert_northeast("cat", [2], [0])
72 >>> ws.board # doctest: +NORMALIZE_WHITESPACE
73 [[None, None, 't'],
74 [None, 'a', None],
75 ['c', None, None]]
76 >>> ws.insert_northeast("at", [0, 1], [2, 1, 0])
77 >>> ws.board # doctest: +NORMALIZE_WHITESPACE

Callers 1

visualise_word_searchFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected