-1

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

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Thank you, works as I should. Just thing: What can I do to avoid a list index out of range error (for example if I would write BOnCoordinate[1000,1000]? A try/except thing seems to be a bit unprofessional
@MichaelBrown try .. except is exactly what you need to do to handle such as errors. IndexError.
Just know the size of your data. The exception should only be thrown if you are actually doing something wrong in your code. It shouldn't be used to tell you when to stop iterating or something like that.
So for example if I know that the file is 10x10, then I just check if x or y is smaller than 10 (or 9 if a 0 counts as well)?
Well you can check the length of the list and the strings. So you'd never need to hard code the sizes.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.