Given an m by n grid of letters, and a list of words, find the location in the g
ID: 3555283 • Letter: G
Question
Given an m by n grid of letters, and a list of words, find the location in the grid where the word can be found. A word matches a straight, contiguous line of letters in the grid. The match could either be done horizontally (left or right) or vertically (up or down). We will not consider words that can be matched diagonally.
The input will be in a file called hidden.txt and your output will be written to a file called found.txt. The format of the input file will be as follows:
There will be k lines in your output file. Each line will have the word that you were search for followed by two integers i and j separated by one or more spaces. The numbers will be right justified and aligned. The number i gives the row and the number j the column of the first letter of the word that you were required to find. Rows and columns are numbered conventionally, i.e. the first row is 1 and the first column is 1. If you do not find a word in the grid then the values for i and j will be0 and 0. Use the full power of the built-in functions associated with strings and lists.
Extra Credit (10 points): Find all the diagonal words. The diagonal words could go either right to left or left to right along any diagonal. Give the row number and the column number of the first letter of the word.
This is the input file (hidden.txt)
This is what the output file should look like (found.txt)
Explanation / Answer
def main(): inFile = open ("hidden.txt", 'r') outFile = open ("found.txt", 'w') count = 0 first_line = inFile.readline() inFile.readline() first_line1 = first_line.split() width = int(first_line1[0]) height = int(first_line1[-1]) grid =[[] * height for i in range(width)] i = 0 while True: firstGrid = inFile.readline() if firstGrid == ' ': break else: firstGrid = firstGrid.replace(' ', '') firstGrid = firstGrid.split() grid[i] = firstGrid i = i + 1 inFile.readline() inFile.readline() word_list = [] while True: wordList = inFile.readline() if wordList == '': break else: word_list.append(wordList.replace(' ', '')) print (word_list) for row in grid[0]: if row in word_list: print ("true") else: print ("false") inFile.close() outFile.close()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.