Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for The Hidden Word by colinmcnicholl
from itertools import zip_longest
def checkio(text, word):
"""Input: Two arguments. A rhyme as a string and a word as a string
(lowercase).
Function finds the given word inside the rhyme in the horizontal
(from left to right) or vertical (from up to down) lines.
Envision the rhyme as a matrix (2D array).
Find the coordinates of the word in the cut rhyme (without whitespaces).
The result must be represented as a list --
[row_start,column_start,row_end,column_end], where
row_start is the line number for the first letter of the word.
column_start is the column number for the first letter of the word.
row_end is the line number for the last letter of the word.
column_end is the column number for the last letter of the word.
Counting of the rows and columns start from 1.
Output: The coordinates of the word as a list.
"""
# Find the word inside the rhyme in the horizontal.
lines = text.replace(" ", "").lower().split('\n')
for row, line in enumerate(lines, start=1):
index = line.find(word)
if index != -1: # If word found.
row_start, row_end = row, row
column_start, column_end = index + 1, index + len(word)
# Find the word inside the rhyme in the vertical.
transposed_array = [list(elem) for elem in zip_longest(*lines, fillvalue='')]
transposed_lines = ["".join(elem) for elem in transposed_array]
for row, line in enumerate(transposed_lines, start=1):
index = line.find(word)
if index != -1: # If word found.
column_start, column_end = row, row
row_start, row_end = index + 1, index + len(word)
return [row_start, column_start, row_end, column_end]
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("""DREAMING of apples on a wall,
And dreaming often, dear,
I dreamed that, if I counted all,
-How many would appear?""", "ten") == [2, 14, 2, 16]
assert checkio("""He took his vorpal sword in hand:
Long time the manxome foe he sought--
So rested he by the Tumtum tree,
And stood awhile in thought.
And as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!""", "noir") == [4, 16, 7, 16]
Jan. 23, 2019