Home > Blockchain >  python principals Tic tac toe input - is a one liner possible?
python principals Tic tac toe input - is a one liner possible?

Time:07-27

The task in python principals is stated as follows:

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 0 in the board.

My solution:

def get_row_col(cor):
    cor.lower().split()
    return (int(cor[1])-1,ord(cor[0]) - 65)

My question is if there is a way to solve it using 1 line (excluding the def function), i.e

def get_row_col(cor):
    return ...

CodePudding user response:

Let me explain a bit your mistake. str type is immutable. It generally means that you cannot change value of some str, what you do behind the scenes is creating new str and pointing to another place in memory. Saying that, all methods of str (like lower or split) creates new thing (another str or list in that case).

Such line

my_str.any_method()

never has an effect and it should be

my_str = my_str.method()

So yeah, you already have 'one liner', but if you really want to have just one line (please, never do that in real code) you could write

get_row_col = lambda cor: (int(cor[1])-1,ord(cor[0]) - 65)

CodePudding user response:

"A", "B", "C" have ASCII numbers

[ord(c) for c in "ABC"]
>>>[65, 66, 67]

same as "1", "2", "3"

[ord(c) for c in "123"]
>>>[49, 50, 51]

So just convert the chars to integer

def get_row_col(cor):
    return (ord(cor.upper()[0])-ord('A'), ord(cor.upper()[1])-ord('1')) 

print(get_row_col("b3"))
>>>(1,2)
  • Related