I'm fairly new to Python and I have to do this exercise where I need to simulate a cat walking on a few lines. If the cat finds a treat ( * ), he eats it, and the position is replaced with floor ( _ ). If the cat finds a hole ( . ), he will fall to next line and keep walking in the same direction. This is the only way for the cat to move to other line. If the cat reaches the end of the line, he changes direction, and walk the line again eating the treats that he did not eat the first time. If the cat doesn't find another hole and reaches the other end of the line, the loop needs to stop. The other way to stop the loop is if the cat finds a hole in the last line. The output should be the amount of treats the cat found on the way.
I'm having a lot of trouble trying to make the cat stop only if has reached both ends of the line. Please help!
The images have examples of the input (black) and how the cat should walk (red).
platforms = []
n = int(input())
for _ in range(n):
platforms.append(list(input()))
# Path simulation
treats = 0
row = 0
column = 0
direction = 1 # 1 represents the right direction and -1 represents the left direction
while True:
if row >= n:
break
if column < 0 or column >= len(platforms[row]):
column -= direction
direction *= -1 # changes direction at the edges of the rows
# Check if the cat reached both ends of the line without finding any hole
if (column == 0 and platforms[row][column] != '.') or (column == len(platforms[row]) and platforms[row][column] != '.'):
break
elif platforms[row][column] == '_':
column += direction
elif platforms[row][column] == '*':
treats += 1
platforms[row][column] = '_' # replaces the treat with floor ( _ )
column += direction
elif platforms[row][column] == '.':
if row == n:
break
if column == 0 or column == len(platforms[row]):
row += 1 # falls to the lower level in the same column
column += direction # moves to the next column in the same row
else:
row += 1 # falls to the lower level in the same column
column += direction # moves to the next column in the same row
print(treats)