Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Tic tac toe input

Here’s the backstory for this challenge: imagine you’re writing a tic-tac-toe game, where the board looks like this:

1:  X | O | X
   -----------
2:    |   |  
   -----------
3:  O |   |

    A   B  C

The board is represented as a 2D list:

board = [
    ["X", "O", "X"],
    [" ", " ", " "],
    ["O", " ", " "],
]

Imagine if your user enters "C1" and you need to see if there’s an X or O in that cell on the board. To do so, you need to translate from the string "C1" to row 0 and column 2 so that you can check board[row][column].

Your task is to write a function that can translate from strings of length 2 to a tuple (row, column). Name your function get_row_col; it should take a single parameter which is a string of length 2 consisting of an uppercase letter and a digit.

For example, calling get_row_col("A3") should return the tuple (2, 0) because A3 corresponds to the row at index 2 and column at index 0in the board.

 

 

==== SOLUTION ====

You can implement the `get_row_col` function in Python by mapping the input string to the corresponding row and column indices on the tic-tac-toe board. Here’s how you can do it:

“`python
def get_row_col(cell):
        # Mapping uppercase letters to column indices
        col_mapping = {‘A’: 0, ‘B’: 1, ‘C’: 2}
        # Extracting row and column indices from the input string
        row = int(cell[1]) – 1 # Subtracting 1 to convert from 1-indexed to 0-indexed
        col = col_mapping[cell[0]]
        return row, col

# Test the function
print(get_row_col(“A3”)) # Output: (2, 0)
“`

Explanation:

1. `def get_row_col(cell):`: This line defines a function named `get_row_col` that takes a single parameter `cell`, which is a string of length 2 consisting of an uppercase letter and a digit.

2. `col_mapping = {‘A’: 0, ‘B’: 1, ‘C’: 2}`: This line creates a dictionary `col_mapping` to map the uppercase letters (A, B, C) to their corresponding column indices (0, 1, 2).

3. `row = int(cell[1]) – 1`: This line extracts the row index from the input string `cell`. Since the rows in the board are 0-indexed (starting from 0), we subtract 1 from the digit character to convert it to a numeric index.

4. `col = col_mapping[cell[0]]`: This line extracts the column index from the input string `cell` using the `col_mapping` dictionary.

5. Finally, the function returns a tuple `(row, col)` containing the row and column indices.

So, when you call `get_row_col(“A3”)`, it returns `(2, 0)` because A3 corresponds to the row at index 2 and column at index 0 in the board.

 

Join the conversation