2017-11-01 4 views
1

그래서이 프로그래밍 숙제를 연구 중이며 현재 한 튜플의 값 쌍을 목록의 튜플 쌍과 비교하는 중이다.쌍의 튜플을 튜플 쌍의 목록과 비교하십시오.

쌍은 기본적으로 x와 y 좌표이며 목록에서 가장 가까운 것을 튜플 쌍으로 찾아야합니다. 예를 들어, 점 (-4, 3)과 목록 [(10, 6), (1, 7), (6, 3), (1, 9)]이있는 경우 가장 가까운 값은 (1, 7)입니다.

이 숫자는 프로그래밍의 무작위 부분에 따라 항상 변경되지만 위의 내용은 함수로 정의됩니다.

def nearest(point, more_points): 
    ''' 
    Finds the nearest point to the base point 
    ''' 
    (x, y) = point 
    for i, j in more_points: 
     a = math.fabs(x - i) 
     tempI = i 
     b = math.fabs(y - j) 
     tempJ = j 
     tempA, tempB = a , b 
     if min(tempA) < a: 

point =() 
my_points = [] 
c = 0 
lpoint = list(point) 
while c < 2: 
    lpoint.append(random.randrange(-5,5,1)) # generate the "point" 
    c += 1 
tpoint = tuple(lpoint) 
c = 0 
colx = [] # x points 
coly = [] # y points 
# generate the points 
while c < 4: 
    colx.append(random.randint(0,10)) 
    coly.append(random.randint(0,10)) 
    c += 1 

my_point = list(zip(colx,coly)) 
print(my_point) 
the_nearest = nearest(tpoint,my_point) 
print(the_nearest) 

내가 뭘하려고 오전 시점에서 Y는 X를 취할 다음 "다른"점을 가지고 차이를 얻을 다음 "가까운 찾기 위해 그것을 사용하는 것입니다 : 여기에 모든 일이 "하지만 나는 길을 잃었고 붙어 있습니다. 포커스는 사용자 정의 함수에 있습니다.

+1

당신이 적절한 들여 쓰기를 확인하기 위해 코드를 편집 할 수 있습니까? 함수에있는 것과 그렇지 않은 것에 대해 확실하지 않습니다. – FunkySayu

+0

@FunkySayu stackoverflow를 사용하지 않아서 미안하지만 – Gary

+0

'if min (tempA) FunkySayu

답변

5

다음과 같은 기능이 2 점 이내의 거리를 계산 가정 : 내가 더 파이썬 가지고 올 수 있지만

def nearest(point, all_points): 
    closest_point, best_distance = None, float("inf") 
    for other_point in all_points: 
     d = distance(point, other_point) 
     if d < best_distance: 
      closest_point, best_distance = other_point, d 
    return closest_point 

:

def distance(point_a, point_b): 
    """Returns the distance between two points.""" 
    x0, y0 = point_a 
    x1, y1 = point_b 
    return math.fabs(x0 - x1) + math.fabs(y0 - y1) 

당신은 모든 점을 반복하고 최소 거리를 찾을 수 있습니다 접근법 :

def nearest(point, all_points): 
    """Returns the closest point in all_points from the first parameter.""" 
    distance_from_point = functools.partial(distance, point) 
    return min(all_points, key=distance_from_point) 

위의 해결 방법에 대한 전반적인 아이디어는 다음과 같습니다. 부분적인 기능을 만들기. 이 부분 함수는 단일 매개 변수를 취해 매개 변수로 주어진 점까지의 거리를 반환합니다. 이것은 lambda other_point: distance(point, other_point)로 다시 쓰여질 수 있지만 이것은 더 예쁘다.

위의 함수는 nearest(point, [])의 빈 목록으로 호출하면 ValueError을 발생시킵니다. 필요한 경우이 경우에 if를 추가 할 수 있습니다.

+0

니스. 나는 min()이 중요한 기능을했다는 것을 몰랐다. – Harvey

+0

여기에 문제가 있습니다. 우리가 지금까지 functools 항목을 사용할 수 있는지 확실하지 않은데 아직까지 Murah의 Python 프로그래밍 교과서에서 사용자 정의 함수를 사용했기 때문에 @FunkySayu – Gary

+0

걱정하지 마십시오. 첫 번째 정의 (두 번째 코드 블록) 또는 람다를 사용하십시오 :) – FunkySayu

0

key 기능을 사용 min() :

#!/usr/bin/env python3 

import math 
from functools import partial 


def distance_between_points(a, b): 
    ax, ay = a 
    bx, by = b 
    return math.sqrt(pow(ax - bx, 2) + pow(ay - by, 2)) 


def nearest(point, more_points): 
    ''' 
    Finds the nearest point to the base point 
    ''' 
    distance_to_point = partial(distance_between_points, point) 
    return min(more_points, key=distance_to_point) 


point = (-4, 3) 
my_points = [(10, 6), (1, 7), (6, 3), (1, 9)] 
n = nearest(point, my_points) 
print(n)