0

Right now, I have the function for a board written out:

def board(canvas, width, height, n):
  for row in range(n+1):
     for col in range(n+1):
        canvas.create_rectangle(row*height/n,col*width/n,(row+1)*height/n,(col+1)*width/n,width=1,fill='white',outline='green')

How do I make an array of integers that corresponds to this board, with every integer initialized as "bad"?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
pubkitty
  • 5
  • 2
  • 1
    @BhargavRao Well, because Python uses type inference we can initialize a string array whose elements will later become integers. – Malik Brahimi Mar 26 '15 at 18:54
  • @MalikBrahimi But that is **not** an *integer* initialized as *bad*. A string is a string and an integer is an integer. Elements of a string array cannot become an integer! Do note that the next time you use an `=` to change your variable value, you are not making your string an integer. You are changing the value of the variable and not the literal value. Thus "bad" is not and can never become an integer! – Bhargav Rao Mar 26 '15 at 18:57
  • 1
    `board = [["bad"]*n for _ in range(n)]` – martineau Mar 26 '15 at 18:57
  • @Martineau It is usually bad practice to create a list with *multiplication* like that. – Malik Brahimi Mar 26 '15 at 19:01
  • possible duplicate of [How to initialize a two-dimensional array in Python?](http://stackoverflow.com/questions/2397141/how-to-initialize-a-two-dimensional-array-in-python) – Bhargav Rao Mar 26 '15 at 19:03
  • @Malik: The way I did it is fine. – martineau Mar 26 '15 at 19:05
  • Found the answer in that that question before I came back here. Sorry, guys! Thanks for your help. – pubkitty Mar 26 '15 at 19:06

1 Answers1

2

Just use a list comprehension, you can later change the contents of the array to integers because Python uses type inference, meaning that we can initialize an array containing strings and change the items to refer to integers.

board = [['bad' for i in range(n + 1)] for j in range(n + 1)]
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • Yes, these wordings are accurate. (you get a + from me, you could have added that an integer can never be "bad") – Bhargav Rao Mar 26 '15 at 19:00
  • @BhargavRao Sorry if I wasn't clear in the comments, but I think you understood what I meant. Array contain references to objects which you can change. I didn't mean that strings become integers, rather the item at any given index can change by changing the reference. – Malik Brahimi Mar 26 '15 at 19:04
  • Np, Forget the comments! You need to be clear in your answers, which you are :) – Bhargav Rao Mar 26 '15 at 19:05