The immutable string

Yesterday I wanted to print a tic-tac-toe.
I wrote this:

import random

values = ["X" if random.randint(0,1) else "O" for _ in range(9)]

tttString = ""
for i in range(3):
for j in range(3):
tttString += "|"
tttString += "-"*3
tttString += "|\n"

print(tttString)

to get the grid:

|---|---|---|
|---|---|---|
|---|---|---|

And then I thought that I could compute the positions for Xs and Os. I even thought of a dict to hold them like:

pos = {1:2,2:6,3:10,4:16,5:20,6:24,7:30,8:34,9:38}

But Python had its own mind on the subject when I tried:

tttString[pos[1]] = "X"

it gave:

TypeError: 'str' object does not support item assignment

I tried

tttString[2] = "X"

but to no avail!
Turns out Python strings are immutable!

My workaround was the following code:

import random

values = ["X" if random.randint(0,1) else "O" for _ in range(9)]

tttString = ""
for i in range(3):
for j in range(3):
tttString += "|"
tttString += "-"*3
tttString += "|\n"

pos = {1:2,2:6,3:10,4:16,5:20,6:24,7:30,8:34,9:38}

for (i,val) in enumerate(values):
tttList = list(tttString)
tttList[pos[i+1]] = val
tttString = "".join(tttList)

print(tttString)

But with a change of the whole logic the following much better code came up:

import random
values = ["X" if random.randint(0,1) else "O" for _ in range(9)]

tttString = ""
for i in range(3):
  for j in range(3):
    tttString += "|"
    tttString += "-" + values[i*j+j] +"-"
    tttString += "|\n"

print(tttString)

If a language restriction makes me write better code then it’s a useful restriction.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s