Home > Back-end >  Finding the minimum result of a list of results
Finding the minimum result of a list of results

Time:04-07

I'm a super beginner to python and know nothing about it and currently for my class we are tasked to find a closest point to a list of other points:

def find_closest(start_point, remaining_points) :
    for element in list(remaining_points) :
        result = distance(start_point, element)
        print(result)

(I defined a distance function that calculates the direct distance between two points)

I then input the following code:

find_closest((1,2),[(3,4),(5,6),(7,8)])

And this gives me answers for the list such like:

2.8284271247461903
5.656854249492381
8.48528137423857

My question is, how do I code into the find_closest function a way to find the minimum value from the result and then print that element's point, i.e: in the answer of simply:

(3,4)

Sorry if this seems too simple, I've tried searching many sources and couldn't find a simple answer as we cant use advanced python and are restricted to if loops and elif etc... Thanks guys!

CodePudding user response:

Solution

You can use the min function of python with the key argument like this:

def find_closest(start_point, remaining_points):
    return min(remaining_points, key=lambda a: distance(start_point, a))

Links for more information

CodePudding user response:

A quick and straightforward solution would be to create a list of results and then corroborate the index with your list of remaining points (because they are inherently lined up). Below is a step-by-step process to achieving this, and at the very bottom is a cleaned-up version of the code.

def find_closest(start_point, remaining_points):
    results = []  # list of results for later use
    for element in list(remaining_points):
        result = distance(start_point, element)
        results.append(result)  # append the result to the list

    # After iteration is finished, find the lowest result
    lowest_result = min(results)
    # Find the index of the lowest result
    lowest_result_index = results.index(lowest_result)
    # Corroborate this with the inputs
    closest_point = remaining_points[lowest_result_index]
    # Return the closest point
    return closest_point

Or to simplify the code:

def find_closest(start_point, remaining_points):
    results = []
    for element in remaining_points:
        results.append(distance(start_point, element))
    
    return remaining_points[results.index(min(results))]
  • Related