Shutterfly OA

我的代码

def closestStraightCity(c, x, y, q):
    city = dict()  # dictionary of form city : [x, y]
    xd = dict()  # dictionary of form x_coordinate : [city1, city2]
    yd = dict()  # dictionary of form y_coordinate : [city1, city2]

    for i in range(len(c)):

        x_val = x[i]
        y_val = y[i]
        city[c[i]] = [x_val, y_val]

        #add x
        if x_val in xd.keys():
            xd[x_val] += [[c[i],y_val]]
        else:
            xd[x_val] = [[c[i],y_val]]

        # add_y
        if y_val in yd.keys():
            yd[y_val] += [[c[i],x_val]]
        else:
            yd[y_val] = [[c[i],x_val]]

    ans = list()
    for ques in q:
        x_check = city[ques][0]
        y_check = city[ques][1]

        minimum = float("inf")
        city_near = "NONE"

        # to check if point is near x co-ordinate
        x_cities_pos = xd[x_check]
        for i in x_cities_pos:
            if (i[0] != ques):
                if(abs(city[i[0]][1] - y_check)<=minimum):
                    minimum = abs(city[i[0]][1] - y_check)
                    city_near = i[0]

        # to check if point is near y co-ordinate
        y_cities_pos = yd[y_check]
        for i in y_cities_pos:
            if (i[0] != ques):
                if (abs(city[i[0]][0] - x_check) <= minimum):
                    minimum = abs(city[i[0]][0] - x_check)
                    city_near = i[0]

        ans.append(city_near)

    return (ans)



if __name__ == '__main__':
    #TC - 1
    c = ["fastcity", "bigbanana", "xyz"]
    x = [23, 23, 23]
    y = [1, 10, 20]
    q = ["fastcity", "bigbanana", "xyz"]
    answer = ["bigbanana", "fastcity", "bigbanana"]
    print(closestStraightCity(c, x, y, q) == answer)

    # TC - 2
    c = ["london", "warsaw", "hackerland"]
    x = [1, 10, 20]
    y = [1, 10, 10]
    q = ["london", "warsaw", "hackerland"]
    answer = ["NONE", "hackerland", "warsaw"]
    print(closestStraightCity(c, x, y, q) == answer)

    # TC - 3
    c = ["green", "red", "blue", "yellow", "pink"]
    x = [100, 200, 300, 400, 500]
    y = [100, 200, 300, 400, 500]
    q = ["green", "red", "blue", "yellow", "pink"]
    answer = ["NONE", "NONE", "NONE", "NONE", "NONE"]
    print(closestStraightCity(c, x, y, q) == answer)