List<string> prod = new List<string>();
prod.Add("dfg");
prod.Add("dfg");
prod.Add("ojj");
prod.Add("dfg");
prod.Add("e");
In the above code prod List has item "dfg" repeated thrice(max count)... I want "dfg" as the output because this item is repeated maximum times. Can anyone help in this
Given a list, the task is to find the number of occurrences of the largest element of the list. Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list.
Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.
Method 1 : Naive method + max() In this method, we simply iterate through the string and form a key in a dictionary of newly occurred element or if element is already occurred, we increase its value by 1. We find maximum occurring character by using max() on values.
Not the absolutely most efficient, but it works:
var maxRepeatedItem = prod.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.First().Key;
This is more efficient:
var maxRepeatedItem = prod.GroupBy(x => x)
.MaxBy(x => x.Count())
.First().Key;
but it requires MoreLinq's extension MaxBy
EDIT (as per comment) :
If you want all the max repeated elements in case of ties, here's a possible solution:
var grouped = prod.ToLookup(x => x);
var maxRepetitions = grouped.Max(x => x.Count());
var maxRepeatedItems = grouped.Where(x => x.Count() == maxRepetitions)
.Select(x => x.Key).ToList();
You can use LINQ:
string maxRepeated = prod.GroupBy(s => s)
.OrderByDescending(s => s.Count())
.First().Key;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With