How can I write an algorithm without the build-in function to do this?
you can't really do without the built in functions.I think you just don't want built in collections tools but you want to write an algorithm from scratch .I don't think it is the best way but you can use this:
def most_common(somelist: list) -> dict:
somelist_dict = {}
somelist_list = []
result={'mostcommon':'','length':0,'content':[]}
maxi=0
word=''
for x in somelist:
try:
somelist_dict[x[0]].append(x[1])
except:
somelist_dict[x[0]] = []
somelist_list.append(x[0])
somelist_dict[x[0]].append(x[1])
for i, j in enumerate(somelist_list):
if i == 0:
word = j
maxi = len(somelist_dict[j])
else:
tmp = len(somelist_dict[j])
if maxi < tmp:
word = j
maxi = tmp
result["mostcommon"]=word
result['length']=maxi
for k in somelist_dict[word]:
result['content'].append(k)
return result
somelist=[['fruit','apple'],['fruit','peach'],['fruit','banana'],['animal','cat'],['animal','sheep']]
print(most_common(somelist))
and the ouput is:
{'content': ['apple', 'peach', 'banana'], 'length': 3, 'mostcommon': 'fruit'}