N
N
Nikolai Sidorenko2014-11-18 14:27:25
Python
Nikolai Sidorenko, 2014-11-18 14:27:25

Why is the problem solved incorrectly?

In python, I solve a problem where you need to enter the coordinates of a chess cell and find all possible options for a knight to move from it.
For example
input: B7 | output D6, C5, D8, A5 --- This is the correct answer
input: B7 | output H6, C5, H8, A5 --- This is what my algorithm outputs
Here is the code, for some reason part of the coordinates is correct.

a = str(input('Введи координаты (типа D5): '))
alfavit = ['A','B','C','D','E','F','G','H']
doska = ([0,0,0,0,0,0,0,0]),([0,0,0,0,0,0,0,0]),([0,0,0,0,0,0,0,0]),([0,0,0,0,0,0,0,0]),([0,0,0,0,0,0,0,0]),([0,0,0,0,0,0,0,0]),([0,0,0,0,0,0,0,0]),([0,0,0,0,0,0,0,0])
chisla = [1,2,3,4,5,6,7,8]

#Создаю доску и нахожу координаты
for x in range(8):
    for y in range(8):
        doska[x][y] = str(alfavit[x] + str(chisla[y]))
        if a == doska[x][y]:
            coord1, coord2 = x, y

#В помощь проэкция доски
for i in range(8): 
    for j in range(8):
        if j == 7:
            print(doska[i][j],end = '\n')
        else:
            print (doska[i][j], end = ' ')

#Вычисляю куда пойдет 
for o in [-1,1]:
    for d in [-2,2]:
        if coord1 + o > 7 or coord2 + o > 7 or coord1 + d > 7 or coord2 + d > 7 or coord1 + o < -1 or coord2 + o < -1 or coord1 + d < -1 or coord2 + d < -1:
            continue
        else:
            print(doska[coord1 + o][coord2 + d])
            print(doska[coord1 + d][coord2 + o])#Тут скоррее всего проблемма

By the way, is there any function for outputting coordinates in python?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
throughtheether, 2014-11-18
@NSidorov

This condition:

if coord1 + o > 7 or coord2 + o > 7 or coord1 + d > 7 or coord2 + d > 7 or coord1 + o < -1 or coord2 + o < -1 or coord1 + d < -1 or coord2 + d < -1:
            continue
else:
    ...

, in my opinion, is incorrect, it cuts off the correct answers and allows the wrong ones (H8 in the example with the original cell B7). If I were you, I would rewrite the body of the loop like this:
if 0<=coord1 + o<=7 and 0<=coord2 + d<=7:
        print(doska[coord1 + o][coord2 + d])
if 0<=coord1 + d<=7 and 0<=coord2 + o<=7:
        print(doska[coord1 + d][coord2 + o])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question