'''Created on 10/01/2014# My first foray in python# min_abs_sum_of_two takes an Integer Array and returns the lowest absolute sum of two integers# I did not include checking for the following: array length, non integer characters.@author: BeauR'''import timeimport sysdef min_abs_sum_of_two(listOfNums):#init y as last array placey = len(listOfNums)-1#init x as first array placex = 0#set current min to arbitrary max possible integercurrentMin = sys.maxsize#quicksort array into ascending orderquicksort(listOfNums, x, y)#while x is less than y to ensure they never overlap array placeswhile (x < y):#if the current calculation is less than currentMinif abs(listOfNums[x]+listOfNums[y]) < currentMin:#store new minimumcurrentMin = abs(listOfNums[x]+listOfNums[y])#if the sum of arr[x] & arr[y] is greater than zero#x no longer need to be increased as its at optimum minimum valueif listOfNums[x]+listOfNums[y] < 0:#increment search pointer xx = x + 1else:#decrement search pointer yy = y -1return(currentMin)def quicksort(list, start, end):if start < end: # If there are two or more elements...split = partition(list, start, end) # ... partition the sublist...quicksort(list, start, split-1) # ... and sort both halves.quicksort(list, split+1, end)else:returndef partition(myList, start, end):pivot = myList[start]left = start+1right = enddone = Falsewhile not done:while left <= right and myList[left] <= pivot:left = left + 1while myList[right] >= pivot and right >=left:
right = right -1if right < left:done= Trueelse:# swap placestemp=myList[left]myList[left]=myList[right]myList[right]=temp# swap start with myList[right]temp=myList[start]myList[start]=myList[right]myList[right]=tempreturn rightstart_time = time.clock()print(min_abs_sum_of_two(listOfNums = [-6, -5, -4, -3, 1]))print(time.clock() - start_time, "seconds")
Sunday, 12 January 2014
Python: Minimum absolute sum of two integers in an Array
So I was given this problem and figured I would share my solution for others. I believe the Time Complexity to be O(n log n) due to Quicksort being O(n log n). I could be wrong though!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment