Created
October 23, 2022 05:53
-
-
Save Shamim-38/817ec9ff07216d155777af4b25326077 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Try to find max in list: | |
l = [1,2,3,4,4] | |
num = max(l, key=lambda x:l.count(x)) # num will be 4 | |
the you can get the count of num. | |
l.count(num) # this wil returns 2 | |
in the other hand as @buddemat said(Here), it is better to: | |
from collections import Counter | |
l = [1,2,3,4,4] | |
c = Counter(l) | |
c.most_common()[0] | |
will give you | |
(4,2) # 4 is a maximum number and 2 is number of occurrence. | |
First, find the maximum and use count | |
l1 = [1, 2, 3, 4, 4] | |
maximum = max(l1) | |
count = l1.count(maximum) | |
You can replace the maximum function by yourself. If you don't like to use the built-in function by following the ways | |
def max(l1): | |
maximum = l1[0] | |
for el in l1: | |
if maximum< el: | |
maximum = el | |
return maximum | |
The above function will check each element of the list iteratively. | |
def maximum(l1): | |
if len(l1) == 1: | |
return l1[0] | |
if len(l1) == 2: | |
if l1[0]> l1[1]: | |
return l1[0] | |
else: | |
return l1[1] | |
else: | |
max1 = maximum(l1[:len(l1)//2]) | |
max2 = maximum(l1[len(l1)//2:]) | |
if max1 > max2: | |
return max1 | |
else: | |
return max2 | |
The above function is using the divide and conquer approach to find the maximum which time complexity is logn |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment