Dec-25-2018, 12:36 AM
I've done some refactoring. Everything should still work,; I just made it more pythonic.
You can't have an infinite loop - for loops are inherently finite - but the code does have an exponential problem in get_distance(). If each list contains three items and each item is a list of three numbers, then the code iterates through them a total of 27 times; four items each would be 64 times; etc.
You can't have an infinite loop - for loops are inherently finite - but the code does have an exponential problem in get_distance(). If each list contains three items and each item is a list of three numbers, then the code iterates through them a total of 27 times; four items each would be 64 times; etc.
import csv import math import statistics def load_from_csv(filename): with open(filename,'r') as csvfile: return list(csv.reader(csvfile,delimiter=',')) def get_distance(test1,test2): euclidean_list_complete = [] outer_length = len(test1) inner_length = len(test1[0]) for i in range(outer_length): euclidean_list = [] for j in range(outer_length): euclidean = 0 for k in range(inner_length): euclidean += pow(float(test2[i][k]) - float(test1[j][k]), 2) euclidean_list.append(math.sqrt(euclidean)) euclidean_list.sort(reverse = True) euclidean_list_complete.append(euclidean_list) return euclidean_list_complete def get_standardised_matrix(matrix): col = 0 mycolunmlist = [item[col] for item in matrix] print('My colunm List :', mycolunmlist) for item in mycolunmlist: standard = (item[col] - ave(mycolunmlist)) / get_standard_deviation(matrix, col) matrix.insert(item[col], standard) return matrix def ave(matrix): return sum(matrix)/len(matrix) def get_standard_deviation(matrix, col): return statistics.stdev([item[col - 1] for item in matrix]) def get_k_nearest_labels(rowmatrix, matrix, new_matrix, k): file_open = load_from_csv(rowmatrix) print(file_open[0]) fopen = load_from_csv(matrix) newfile = load_from_csv(new_matrix) for item in fopen: print(item) print( 'Euclidean Distance between two matrix :\n', get_distance(file_open[0], item) ) def main(): print('Data from "Data.csv" file :', load_from_csv('Data.csv')) print( 'Euclidean Distance between two matrix :\n', get_distance( [[2,3,5],[12,3,5],[2,3,6]], [[1,2,3],[3,4,6],[4,5,8]] ) ) print('The Standard Deviation of the elements in the column number passed as a parameter :', get_standard_deviation([[2,5,8],[4,8,2]],1)) print('Average of a matrix :', ave([2,3,4])) print('standardised matrix is :', get_standardised_matrix([[2,5,8],[4,8,2]])) main()