Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Hypercube by PythonLearner
from collections import Counter
from itertools import chain, product
from typing import Tuple, List, Iterator
def get_neighbours(node: Tuple[int, int], height: int, width: int) -> Iterator[Tuple[int, int]]:
shifts = ((0, 1), (1, 0), (-1, 0), (0, -1))
neighbours = ((node[0] + shift[0], node[1] + shift[1]) for shift in shifts)
return (neighbour for neighbour in neighbours if 0 <= neighbour[0] < height and 0 <= neighbour[1] < width)
def has_letters(grid: List[List[str]], letters: str, current: Tuple[int, int]) -> bool:
if not letters:
return True
height = len(grid)
width = len(grid[0])
variants = [neighbour for neighbour in get_neighbours(current, height, width)
if grid[neighbour[0]][neighbour[1]] == letters[0]]
return variants and any(has_letters(grid, letters[1:], variant) for variant in variants)
def normalize_grid(grid: List[List[str]]) -> List[List[str]]:
return [[grid[i][j].lower() for j in range(len(grid[0]))] for i in range(len(grid))]
def has_word(grid: List[List[str]], word: str) -> bool:
height = len(grid)
width = len(grid[0])
normalized_grid = normalize_grid(grid)
word_letters = Counter(word)
grid_letters = Counter(letter for letter in chain(*normalized_grid) if letter in word_letters)
starts = ((i, j) for i, j in product(range(height), range(width)) if normalized_grid[i][j] == word[0])
return (set(word_letters) == set(grid_letters)
and all(grid_letters[letter] >= word_letters[letter] for letter in grid_letters)
and any(has_letters(normalized_grid, word[1:], start) for start in starts))
def hypercube(grid: List[List[str]]) -> bool:
return has_word(grid, "hypercube")
if __name__ == '__main__':
print("Example:")
print(hypercube([
['g', 'f', 'H', 'Y', 'v'],
['z', 'e', 'a', 'P', 'u'],
['s', 'B', 'T', 'e', 'y'],
['k', 'u', 'c', 'R', 't'],
['l', 'O', 'k', 'p', 'r']]))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert hypercube([
['g', 'f', 'H', 'Y', 'v'],
['z', 'e', 'a', 'P', 'u'],
['s', 'B', 'T', 'e', 'y'],
['k', 'u', 'c', 'R', 't'],
['l', 'O', 'k', 'p', 'r']]) == True
assert hypercube([
['H', 'a', 't', 's', 'E'],
['a', 'Y', 'p', 'u', 'B'],
['a', 'a', 'P', 'y', 'U'],
['x', 'x', 'x', 'E', 'C'],
['z', 'z', 'z', 'z', 'R']]) == False
print("Coding complete? Click 'Check' to earn cool rewards!")
Nov. 6, 2019