Learn coding by simple questions

Problem 1: Find mode of a list of numbers
def test(func):
"""
Test efficiency of the algorithm in term of time and accuracy
"""
start = time.perf_counter()
series1 = [1,2,3,4,1]
ans1 = 1
if (func(series1) == ans1) | (func(series1) == [ans1]):
print('Pass case 1')
else:
print('Fail case 1')
series2 = [11,22,1,3,4,2,2,1]
ans2 = 1,2 #there should be two modes in this series
if (func(series2) == ans2) | (func(series2) == [ans2]):
print('Pass case 2')
else:
print('Fail case 2')
series3 = [random.randint(1,1000) for i in range(10**7)]
func(series3)
end = time.perf_counter()
print('Time elapsed:' , end - start)
"""
mode in library statistics
"""
test(statistics.mode)
"""
Use pandas.mode
"""
def use_mode_in_pandas(series):
df = pd.DataFrame(series)
return list(df.mode(axis = 0)[0])
"""
Use max function
"""
def use_max(series):
return max(set(series), key=series.count)
"""
Use Counter in library collections
"""
from collections import Counter
def use_counter(series):
counter = Counter(series)
max_count = max(counter.values())
mode = [k for k,v in counter.items() if v == max_count]
return mode
def find_mode(list_numbers):
"""
if list has no element so there is no mode, otherwise there may be one or many modes
Will build a dictionary where keys are distinc elements of input, and values are their frequencies in the series
- input:
list_numbers: list of numbers in a series, type list
- output: print list of modes if there is at least a mode, type list. Else print 'Empty list. There is no mode'
"""
if len(list_numbers) == 0:
return print('Empty list. There is no mode')
else:
set_numbers = set(list_numbers)
dict_numbers = dict({})
for x in set_numbers:
dict_numbers[str(x)] = 0
for x in list_numbers:
dict_numbers[str(x)] += 1
result = [int(x) for x in dict_numbers if dict_numbers[x] == max(dict_numbers.values())]
return result

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store