Общее количество ходов между двумя точками на карте ⇐ Python

Программы на Python
Anonymous
Общее количество ходов между двумя точками на карте

Сообщение Anonymous »

найдите расстояние (x представляет расстояние) между двумя точками (p представляет расстояние) на двухмерной карте 5x5. входные данные представляют собой строку, где каждая запятая представляет следующую строку или уровень. вы можете двигаться только вверх, вниз, влево, вправо. Пример: xxxpx,xxxxxx,xxxxx,xxxpx,xxxxx.
ответ здесь 2.

Код: Выделить всё

#shortest distance between two point, with x representing distance
import numpy as np
map= input()
lst = []
#filtering out commas
for points in map:
if points.isalpha()==True:
lst.append(points)
#converting list of points to array
axis= np.array(lst)
#turning 1d array to 5d
twoD_axis= axis.reshape(5,5)
#to collect index of array with "p"
row=[]
#to collect index of "p" in array
column=[]
count=-1
#iterating through array,checking for "p"and using "count" to get index of array with "p"
for i in twoD_axis:
count+=1
if "p" in i:
#keeping index of p in "row"
row.append(count)
count_2=-1
#iterating through array with "p",using "count" to get index of first "p"
for i in twoD_axis[row[0]]:
count_2+=1
if i=="p":
#keeping index of first p in "column"
column.append(count_2)
count_3=-1
#iterating through array with "p",using "count" to get index of second "p"
for i in twoD_axis[row[1]]:
count_3+=1
if i=="p":
#keeping index of second p in "column"
column.append(count_3)
#subtracting indexes of ps, to get number of xs going down
vertical= row[1]-row[0]
#subtracting indexes of ps, to get number of xs going left or right
horizontal= column[1]-column[0]
#summming all xs
print(vertical+horizontal)

Я обнаружил, что математически мы можем получить количество xs, если бы не вертикальное и горизонтальное движение, вычитая индекс p. Он получает индекс массива с помощью ps, вычитание его дает нам xs между ними по вертикали, а вычитание индекса p в массиве помогает нам с xs по горизонтали. в этом тестовом запуске p был применен к тем же строкам, чего я не ожидал. Я не знаю, что еще попробовать, но это работает для p в разных строках.

Подробнее здесь: https://stackoverflow.com/questions/790 ... s-on-a-map

Вернуться в «Python»