Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Third 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).
Output: The coordinates of the word."""
lines = text.replace(" ", "").lower().split('\n')
for row, line in enumerate(lines, start=1):
index = line.find(word)
if index != -1:
row_start, row_end = row, row
column_start, column_end = index + 1, index + len(word)
break
transposed_lines = [''.join(l) for l in zip_longest(*lines, fillvalue='')]
for row, line in enumerate(transposed_lines, start=1):
index = line.find(word)
if index != -1:
column_start, column_end = row, row
row_start, row_end = index + 1, index + len(word)
break
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]
May 14, 2019