Skip to content

Instantly share code, notes, and snippets.

@270ajay
Created February 18, 2020 12:18
Show Gist options
  • Save 270ajay/ebd9865b4e2f92c9d37ac5d520db746e to your computer and use it in GitHub Desktop.
Save 270ajay/ebd9865b4e2f92c9d37ac5d520db746e to your computer and use it in GitHub Desktop.
Stress test
import time
import random
'''Course: https://www.coursera.org/learn/algorithmic-toolbox#about'''
def maxPairwiseProductSlow(numberList):
'''prints max product between any two numbers in the numberList
slow approach'''
result = 0
lenOfNumList = len(numberList)
for i in range(lenOfNumList):
for j in range(lenOfNumList):
if numberList[i] * numberList[j] > result:
result = numberList[i] * numberList[j]
return result
def maxPairwiseProductFast(numberList):
'''prints max product between any two numbers in the numberList
fast approach'''
lenOfNumList = len(numberList)
maxIndex1 = -1
for i in range(lenOfNumList):
if (maxIndex1 == -1) or (numberList[i] > numberList[maxIndex1]):
maxIndex1 = i
maxIndex2 = -1
for j in range(lenOfNumList):
if (maxIndex1 != maxIndex2) and (maxIndex2 == -1 or numberList[j] > numberList[maxIndex2]):
maxIndex2 = j
return numberList[maxIndex1] * numberList[maxIndex2]
def stressTestMaxPairwiseProductFunctions(minLenOfList, maxLenOfList, minRandomNumber, maxRandomNumber, maxSeconds):
'''compares the results of two functions (maxPairwiseProductSlow, maxPairwiseProductFast) for same input
which is randomly generated. If the results are wrong, it stops. Otherwise, it will stop after maxSeconds'''
startTime = time.time()
endTime = time.time() - startTime
while (endTime <= maxSeconds):
lenOfNumList = random.randrange(minLenOfList, maxLenOfList)
print("length of list: ", lenOfNumList)
numberList = []
for i in range(lenOfNumList):
numberList.append(random.randrange(minRandomNumber, maxRandomNumber))
print("sequence of random numbers: ", numberList)
result1 = maxPairwiseProductSlow(numberList=numberList)
result2 = maxPairwiseProductFast(numberList=numberList)
if result1 != result2:
print("Wrong answer found: ", result1, " ", result2)
break
else:
print("OK")
endTime = time.time() - startTime
print("\nThere was no wrong answer found in "+str(maxSeconds)+" seconds\n")
if __name__ == '__main__':
stressTestMaxPairwiseProductFunctions(minLenOfList=2, maxLenOfList=11, minRandomNumber=0, maxRandomNumber=99999, maxSeconds=10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment