I was doing a puzzle on Coderbyte, and here is what the puzzle stated:
Have the function
SimpleMode(arr)take the array of numbers stored in arr and return the number that appears most frequently (the mode). For example: if
[10, 4, 5, 2, 4]the output should be
4. If there is more than one mode return the one that appeared in the array first (i.e.
[5, 10, 10, 6, 5]should return
5because it appeared first). If there is no mode return
-1. The array will not be empty.
import time from random import randrange def SimpleMode(arr): bestMode=0 numTimes=0 for x in range(len(arr)): if len(arr)>0: currentNum=arr currentMode=0 while currentNum in arr: currentMode+=1 arr.remove(currentNum) if currentMode>numTimes: numTimes=currentMode bestMode=currentNum else: break if numTimes==1: bestMode=-1 return bestMode start_time = time.time() numbers = [randrange(1,10) for x in range(0, 1000)] print(SimpleMode(numbers)) print("--- %s seconds ---" % (time.time() - start_time))
I also realize I can use other programs, but I am just looking for a way to optimize this one.