Reputation: 135
Yesterday I found the following CP task in the internet:
You are provided with a text file (.txt) in which only A's and B's are written.
Read the file and find out how many 3x3 squares of B's were written in the file.
Example txt file:
ABBBAAA
ABBBABA
BBBBBAA
-> in this case there would be one 3x3 square out of B's
I found the task very exciting and therefore started to develop a Python program to solve the task.
Unfortunately my implementation fails because my program splits the text file into a kind of coordinate system and then stores all x and y values of the B's in two different arrays. It is a bit complicated to explain, but my program failed as soon as there were more than the 3 B's of one square in one line. For this reason it would be very useful for the further development of the program to be able to call a method with two parameters, which returns with the help of true/false, if there is a B at the given coordinate.
Perfect Function:
BOnCoordinate[2, 3] # x, y
-> returns True or false
Does anyone have an idea how I could implement it? Unfortunately I have no experience with this and I can't find a useful tutorial on the internet. Many thanks in advance
Upvotes: -1
Views: 63
Reputation: 21609
Here's how it could be done.
Just read in the text file and turn it into a list of strings. Then you can individually query the values by coordinate (strings can be accessed by index just like lists).
Python lists and strings can be indexed using negative indices, which isn't what we want here. So we can also check for negative indices and throw an exception if we are passed one.
with open('data.txt') as f:
result = [line.strip() for line in f]
def BOnCoordinate(x, y):
if x < 0 or y < 0:
raise ValueError('negative indices not allowed')
return result[x][y] == 'B'
print(BOnCoordinate(1,1))
FWIW. It may be more efficient to search the lines for the string "BBB"
rather than individually checking each coordinate.
Upvotes: 1