A function that returns a string which resemples a playing board in python

mmmmmm

I want to write a function that returns a square playing board containing '*' and ' ' based on the input number.

The intended output should be like this:

board_of_5 = (
    ' * * \n'
    '* * *\n'
    ' * * \n'
    '* * *\n'
    ' * * \n'
)
    
board_of_10 = (
    ' * * * * *\n'
    '* * * * * \n'
    ' * * * * *\n'
    '* * * * * \n'
    ' * * * * *\n'
    '* * * * * \n'
    ' * * * * *\n'
    '* * * * * \n'
    ' * * * * *\n'
    '* * * * * \n'
)

Here is my current code, which produces an output on a single line, and with no offset on alternating lines:

def get_playing_board(num):
    string = ''
    for i in range(num):
        for j in range(num):
            if j % 2 == 0:
                string += ' '
            elif j % 2 != 0:
                string += '*'
        print(string)
    return string

get_playing_board(5)

How do I introduce an offset and newlines? How do I loop over the rows?

My idea is to add '*' or blank space based on even or odd numbers and loop for each row and col.

However, I cannot get the intended chart board.

Mad Physicist

The thing that goes into a given row, column depends on the relationship of the row and column index. Specifically, if both are even or odd (have the same parity), the element will be ' '. If they are not the same parity, the element will be a '*'.

The simplest way to check parity is with

if (i % 2) == (j % 2):

The parity of a number is encoded in the last bit: 1 for even, 0 for odd. You can therefore check for sameness using the XOR operator:

if (i ^ j) & 1:

In this case & 1 removes the last bit using bitwise AND.

To insert a newline at the end of each row, you just need to add that at the end of the outer loop:

def get_playing_board(num):
    board = ''
    for i in range(num):
        for j in range(num):
            board += ' *'[(i ^ j) & 1] # The index expression is 0 or 1
        board += '\n'
    return board

get_playing_board(5)

There is a clever alternative to manually generating each row. Instead, you can generate a string that is one element longer than num and grab a subset for each row:

def get_playing_board(num):
    row = ' *' * ((num + 2) // 2)
    board = ''
    for i in range(num):
        board += row[i % 2:num + i % 2] + '\n'
    return board

You can write either approach as a one-liner:

'\n'.join(''.join(' *'[(i ^ j) & 1] for j in range(num)) for i in range(num))
'\n'.join((' *' * ((num + 2) // 2))[i % 2:num + i % 2] for i in range(num))

I don't particularly recommend the bottom two approaches.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

playing board function in python

Implementing a function which returns function definition as string

pinvoke to function which returns string array

Junit test function which returns a string

Unable to compile function which returns parts of a string

Function which returns a TABLE after splitting a string

Calling C++ function which accepts and returns std::string from Python

TypeScript: function that returns a generic Type which extends Record<string, string>

function which returns true is the string is in upper-case using XSLT

User defined function returns value error which should be string

Create a function which takes in a float as input and returns a string containing a number

Create a function in python, which given an integer returns a string. For example:- 1 maps to a, 26 to z, 27 to aa, 50 to ax

Python function which split string by ',' and ignore ':'

Python: Calling a function with a string returns the description of the argument

Python: String manipulation function error, returns "None"

Function which returns function scheme

Writing a function which accepts two strings and returns True in python 3

Test a function in Python which merges files and returns nothing

write a function which accepts a string and returns a new string with only the capital letters passed to the string

Testing a function which returns an object that returns a function which return a boolean

Implement a function which returns a pointer

A Function Which Returns Parent Functions

Function which returns multiple values

Trying to make function which takes string as input and returns no. of words in whole string

Function returns boolean not string

The function returns empty string

How to test function which returns function with parameters?

Scala type mismatch in function which returns Double => String when "return" keyword is used

can't define a function which returns std::vector<string> written in jupyter notebook (ROOT kernel)

TOP Ranking

HotTag

Archive