0
functions python
How can I create a function that goes through the numbers of a list and know which element is repeated the most? without for in or .count
3 odpowiedzi
+ 3
Do you mean repeated over the full list, or repeated in direct succession?
For the first option, this would work:
def f(arr, d):
if not arr:
return max(d, key=d.get)
if arr[0] not in d:
d[arr[0]] = 1
else:
d[arr[0]] += 1
return f(arr[1:], d)
print(f([1, 3, 1, 4, 1, 2, 4, 1, 5, 4, 5, 1], {}))
0
Do not reinvent the wheel!
Use python predefined functions as follows! Take into consideration that "Counter" with uppercase "C"!
-----------------------------------------
from collections import Counter
def most_com(arr):
return Counter(arr).most_common(1)[0][0]
- 3
And here I thought someone would ask for a failed trial code or something 🤣🤣🤣