[Python] total number of moves between two points on a map

Discussão em 'Python' iniciado por Stack, Outubro 2, 2024.

  1. Stack

    Stack Membro Participativo

    find the distance(x representing distance) between two points(p representing distance) in a 5x5 2d map. the input is a string, with each comma representing next line or level. you can only move up,down,left,right. Example: xxxpx,xxxxx,xxxxx,xxxpx,xxxxx. the answer here is 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)




    I discovered that mathematically, we could get the number of xs but for vertical and horizontal movement, by subtracting the index of p. It gets the index of the array with ps, subtracting it would give us the xs between them vertically, and subtracting the index of p in array, helps us with xs horizontal. this test run tried p on the same rows, which I wasn't expecting. I don't know what else to try,but it works for p on different rows.

    Continue reading...

Compartilhe esta Página