0

I'm writing a function called init_carre(tab) that needs to place 9 "X" in the center of a board. This is the code I have written so far:

from copy import deepcopy 
n = int(input("Nombre de colonnes et lignes? "))

def initialisation():
    board = [["." for i in range(n)]for j in range(n)] 
    return board

def affichage(tab):
    t = 0       
    while t<n:             
        for a in tab:
            print("".join(a)) 
            t += 1 
            
def init_carre(tab):
    tableau2 = deepcopy(tab) 
    bacterie = "X" 
    ligne = round(n/2) 
    colonne = round(n/2) 
    tableau2[ligne-1][colonne] = bacterie    #Need to loop this part  !!!!!!!
    tableau2[ligne-1][colonne-1] = bacterie 
    tableau2[ligne-1][colonne-2] = bacterie
    tableau2[ligne-2][colonne] = bacterie
    tableau2[ligne-2][colonne-1] = bacterie
    tableau2[ligne-2][colonne-2] = bacterie
    tableau2[ligne][colonne] = bacterie
    tableau2[ligne][colonne-1] = bacterie
    tableau2[ligne][colonne-2] = bacterie        
    return tableau2 
   
            
affichage(initialisation())
print("")
affichage(init_carre(initialisation()))

I need help to loop the lines that start in the comment "Need to loop this part" and I appreciate if you have any advice on how to improve the code

1 Answer 1

2

You can achieve that by 2 nested loops like this:

for i in range(3):
    for j in range(3):
        tableau2[ligne-i][colonne-j] = bacterie 

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

2 Comments

And if you want ligne and colonne to specify the center of the square of X's, you could change range(3) to [-1, 0, 1] or range(-1, 2). It's also a good idea to check that (ligne-i, colonne-j) aren't outside the tableau2 and aren't negative.
If the answer helped you please consider accepting it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.