diff options
| author | Ryan Thompson <i@ry.ca> | 2024-07-01 13:31:33 -0600 |
|---|---|---|
| committer | Ryan Thompson <i@ry.ca> | 2024-07-01 13:31:33 -0600 |
| commit | 890142337dfa2da9840675b0ef134b8dd09cc3af (patch) | |
| tree | 2137c79ace0e3d6631f13348e38597bccc850b5c /challenge-276/ryan-thompson/python/ch-2.py | |
| parent | f18cb7a95e46b9ded70a2d1d932d0bb7b1772a67 (diff) | |
| download | perlweeklychallenge-club-890142337dfa2da9840675b0ef134b8dd09cc3af.tar.gz perlweeklychallenge-club-890142337dfa2da9840675b0ef134b8dd09cc3af.tar.bz2 perlweeklychallenge-club-890142337dfa2da9840675b0ef134b8dd09cc3af.zip | |
rjt's Week 276 solutions and blog
Diffstat (limited to 'challenge-276/ryan-thompson/python/ch-2.py')
| -rwxr-xr-x | challenge-276/ryan-thompson/python/ch-2.py | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/challenge-276/ryan-thompson/python/ch-2.py b/challenge-276/ryan-thompson/python/ch-2.py new file mode 100755 index 0000000000..08aff757c1 --- /dev/null +++ b/challenge-276/ryan-thompson/python/ch-2.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +# +# ch-2.py - Maximum Frequency +# +# 2024 Ryan Thompson <rjt@cpan.org> + +# First identify which number(s) appear most often in the list, +# then return the count of all such numbers. Ex. 1, 2, 2, 4, 1, 5 +# should return 4, because the matching numbers are 1,1,2,2 (freq:2) +def max_freq(ints): + # Annoying special case for empty list + if len(ints) == 0: + return(0) + + # Build the frequency table (freq[n] = # of times n is in ints) + freq = {} + for n in ints: freq[n] = freq.setdefault(n,0) + 1 + + max_freq = max(freq.values()) # Maximal frequency + + return(sum(filter(lambda x: x == max_freq, freq.values()))) + +# Examples +print(max_freq([1, 2, 2, 4, 1, 5])) # 4 +print(max_freq([1, 2, 3, 4, 5])) # 5 +print(max_freq([1, 2, 2, 4, 6, 1, 5, 6])) # 6 +print(max_freq(['a', 'a', 'b', 'a', 'b', 'b', 'c'])) # 6 +print(max_freq([3.1415926])) # 1 +print(max_freq([])) # 0 |
