1

So I have code for a 2048 board:

count = 0
for i in range(16):
    print(nlist[i], end = ' ')
    count += 1
    if count == 4:
        print("")
        count = 0

and this works fine if all the values are single digit numbers:

0 0 0 8
0 4 0 0 
0 0 2 2
0 0 0 0 

but if I have multiple numbers with more than 1 digit:

16 0 2 2048
8 2 32 64
2 2 0 0
2048 2048 4096 4096

All the spacing gets messed up. Is there any fix for this?

J. Doe
  • 1,475
  • 2
  • 9
  • 17

2 Answers2

1

Avoid writing custom functions for doing this. There are lots of python packages out there that can print stuff in a neat table.

My suggestion would be to use PrettyTable

from prettytable import PrettyTable
t = PrettyTable(header=False, border=False)
for i in range(0,16,4):
    t.add_row(range(i, i+4))

print t
# 0   1   2   3  
# 4   5   6   7  
# 8   9   10  11 
# 12  13  14  15 
Sunitha
  • 11,777
  • 2
  • 20
  • 23
0

As Keatinge mentions in the comment, iterate over the array before printing and find the longest number.

length = max(map(lambda x: len(str(x)), nlist)) + 1

We take nlist, figure out the length of each number when written as text, then take the maximum and add one (the +1 is so that there's a space between the numbers). Then, inside the loop, we stringify the number we're looking at and add spaces as needed.

text = str(x)
text += ' ' * (length - len(text))

Complete example:

count = 0
length = max(map(lambda x: len(str(x)), nlist)) + 1
for i in range(16):
    text = str(nlist[i])
    text += ' ' * (length - len(text))
    print(text, end = '')
    count += 1
    if count == 4:
        print()
        count = 0
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116