2015-12-07 3 views
0

У меня возникли проблемы с функцией на python, в которой я должен печатать плату picross (я не использую графический интерфейс). Мы должны создать доску из спецификации платы, которая является кортежем вроде этого: e=(((2,), (3,), (2,), (2, 2), (2,)), ((2,), (1, 2), (2,), (3,), (3,))). Совет директоров должен выглядеть следующим образом:python 3 печать picross board

enter image description here

, но я не знаю, как вставить значения кортежа в столбцах и строках. это мой код:

t=[[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [((3,), (2,), (2, 2), (2,)), ((2,), (1, 2), (2,), (0,))]] 

j=0 

for i in t[0]: 

    if j == 4: 

     print(" "*len(t[1][0])+"|") 
     j=0 
    if i==[0]:  
     print ("[ ? ]", end="") 
     j +=1 
    elif i==[1]: 
     print("[ . ]", end="") 
     j+=1 
    else: 
     print("[ X ]", end="") 
     j+=1 

print(" "*len(t[1][0])+"|") 

печатает все правильно для чисел кортежа, за исключением.

возвращает это:

[ ? ][ ? ][ ? ][ ? ] | 

[ ? ][ ? ][ ? ][ ? ] | 

[ ? ][ ? ][ ? ][ ? ] | 

[ ? ][ ? ][ ? ][ ? ] | 

ответ

0

Вот моя попытка на него:

t = [[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], 
    [((3,), (2,), (2, 2), (2,)), 
     ((2,), (1, 2), (2,), (0,))]] 

board_size = len(t[1][0]) 
cells = t[0] 
hnums = t[1][0] # These are the horizontal numbers 
vnums = t[1][1] # These are the vertical numbers 

# Here I'm building new lists using list comprehension. 
# I've noticed that some of the numbers are missing the second element. 
# For example here ((2,), (1, 2), (2,), (0,)), only the second element (1, 2) has two members. So I had to make sure this condition is taken care of by adding this x[1] if len(x) > 1 which means only take the second element if the length of the total tuple is more than 1. 
# If you haven't seen list comperhension before, you need to look them up because they are a huge topic. 
# at the end of these lines we will have something like this 
# h1 = [' ', ' ', 2, ' '] 
# h2 = [3, 2, 2, 2] 

h1 = [x[1] if len(x) > 1 else " " for x in hnums] 
h2 = [x[0] for x in hnums] 
v1 = [x[1] if len(x) > 1 else " " for x in vnums] 
v2 = [x[0] for x in vnums] 

# Here I'm building the two horizontal lines 
# heading_string will look like this ' {} {} {} {} ' because the board size is 4. Notice that this will work with other sizes if you changed the t variable. 
heading_string = " {} " * board_size 
# Here I'm just calling the format function and passing in the h1 variable. 
# The * will unpack the list. 
# The end result will be ' {} {} {} {} '.format(' ', ' ', 2, ' ') 
# So each parameter of the format function will be replaced with the {} placeholder 
print(heading_string.format(*h1)) 
print(heading_string.format(*h2)) 

# Here I'm just defining a function to take care of the logic of the cell text 
def cell_text(c): 
    if c == [0]: 
     return "?" 
    elif c == [1]: 
     return "." 
    else: 
     return "X" 

row = [] # a row list that will represent the each row of cells 
# for loop using enumerate and starting from 1. So i will equal to 1 in the first loop 
for i, cell in enumerate(cells, 1): 
    row.append(cell_text(cell)) # appending cells to the row list 

    # if i in the current loop is 4, 8, 12, 16 this condition will be true and we need to break the row to create a new one for the next row 
    if i % board_size == 0: 
     row_string = "[ {} ]" * board_size # Same thing as heading_string 
     # Here I'm building the vertical numbers string 
     # The numbers are stored in v1 and v2 
     # and they both have 4 members indexed 0, 1, 2, 3 
     # That's why I'm subtracting 1 from i because i starts from 1 not from 0 because of enumerate(cells, 1). 
     # This will work fine for the first four elements 
     # but in the fifth loop, i = 4 and we actually need v1[0] 
     # and that's why I'm dividing by the board size to get the correct index 
     vnum_string = " " + str(v2[(i-1) // board_size]) + " " \ 
          + str(v1[(i-1) // board_size]) + " |" 
     print(row_string.format(*row) + vnum_string) # Same as before except that I'm adding the vertical numbers string 
     row = [] # Reset the row list 
+0

Он возвращается ошибка в строке 33 говорят, что индексы список должны быть целыми числами, у вас есть какие-либо идеи, почему? – VCanas

+0

Да, это должен быть оператор деления «/» Я должен был изменить его на целочисленное деление «//». Я обновлю ответ. –

+0

большое спасибо! Мне это очень помогает – VCanas

Смежные вопросы