Second try solution in Clear category for The Hidden Word by golosinas
def checkio(text, word):
"""Takes a multiline string in the form of a rhyme and a single secret word as arguments.
Removes the whitespaces and finds the secret word inside the rhyme in the horizontal
(from left to right) or vertical (from up to down) lines. If the word is found returns
the coordinates in a list, as follows:
row_start = line number for the first letter of the word.
column_start = column number for the first letter of the word.
row_end = line number for the last letter of the word.
column_end = column number for the last letter of the word.
Counting of the rows and columns start from 1.
Input: Two arguments. A rhyme text as a string and a word as a string (lowercase).
Output: The coordinates of the word. """
from itertools import zip_longest
# Removes spaces, converts to lower case and split text into a list of strings (lines)
lines = text.replace(" ", "").lower().splitlines()
# Searches horizontally
for i in range(len(lines)):
if lines[i].find(word) == -1:
return [i + 1, lines[i].find(word) + 1, i + 1, lines[i].find(word) + len(word)]
# If not found searches vertically
column = 1
# transpose text, fill missing indexes
for chars in zip_longest(*lines, fillvalue="*"):
if word in "".join(chars):
return ["".join(chars).index(word) + 1, column, "".join(chars).index(word) + len(word), column]
column += 1
#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]
print("Coding complete? Click 'Check' to earn cool rewards!")
Sept. 20, 2020