18.7 LAB: Algorithm Example In this lab you are asked to complete the provided codeso that the...
Question:
18.7 LAB: Algorithm Example
In this lab you are asked to complete the provided codeso that the algorithm calculates "n" nearest neighbours of a givenvector. The point of this exercise it to provide you with anexample of an algorithm, get you to think about how to divide acomplex task into a number of smaller, more manageable steps and toshow you an example of how different data types might be used fordifferent purposes.
A vector in this context is a point in 3dimensional space (x,y,z). It could be used to represent a locationcoordinate e.g. on a google map with altitude. You can image eachvector representing the location of an object and the algorithm istrying to find a number, "n", nearest objects to the object ofinterest.
Some definitions:
- The "n-Nearest Neighbors" of a given vector 'V0' aredefined as its 'n' closest vectors ie those with the shortestdistance to 'V0'.
- The distance between vectors can be calculated usingthe vec_distance function
- Note: vec_distance, and sort_function are provided. You don't need to understand how theywork, but you need to understand what their input and output is. Tounderstand that you can print the input and output of them - thiscan help you figure out what the rest of the code should looklike.
Code:
from math import sqrt
# Function: calculates the distance between two input vectors
def vec_distance(vector1, vector2):
distance = 0.0
for cntr in range(len(vector1)-1):
distance += (vector1[cntr] -vector2[cntr])**2
return sqrt(distance)
# Helper function: returns distance, from position 1 ofdistance_tuple
def get_distance( distance_tuple ):
return distance_tuple[1]
# Function: sorts list of distances
def sort_(distances):
distances.sort(key=get_distance)
return distances
# Return the required number of nearest neighbours
def get_neighbours(data, test_vector, num_neighbours):
#** Your code goes here
pass # remove this
if __name__ == '__main__':
dataset = [
[2.7810836,2.550537003,0.5],
[1.465489372,2.362125076,1.54],
[3.396561688,4.400293529,0.72],
[1.38807019,1.850220317,1.65],
[3.06407232,3.005305973,0.98],
[7.627531214,2.759262235,1.2],
[5.332441248,2.088626775,1.1],
[6.922596716,1.77106367,0.8],
[8.675418651,-0.242068655,1.7],
[7.673756466,3.508563011,0.76]]
number_of_neighbours = int(input())+1
index_of_vector = int(input())
neighbours = get_neighbours(dataset,dataset[index_of_vector], number_of_neighbours)
if neighbours:
for neighbour in neighbours:
print(neighbour)
Hi I need the code part, i tried doing it but nothingsworking
Intermediate Accounting
ISBN: 978-0470616314
IFRS edition volume 2
Authors: Donald E. Kieso, Jerry J. Weygandt, Terry D. Warfield