diff options
| author | Mohammad Sajid Anwar <Mohammad.Anwar@yahoo.com> | 2024-09-25 09:29:21 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-09-25 09:29:21 +0100 |
| commit | 261da1d2c54ab8faab88537076b4248d5abd00f7 (patch) | |
| tree | c60a0327997c7d9759f275323ae120d735726784 /challenge-074/paulo-custodio/python/ch-1.py | |
| parent | 9e56f497ae79225e5a6e041a963741885335d0d0 (diff) | |
| parent | 206c2fce8db1de9b7f82f04a3276005a284b3c40 (diff) | |
| download | perlweeklychallenge-club-261da1d2c54ab8faab88537076b4248d5abd00f7.tar.gz perlweeklychallenge-club-261da1d2c54ab8faab88537076b4248d5abd00f7.tar.bz2 perlweeklychallenge-club-261da1d2c54ab8faab88537076b4248d5abd00f7.zip | |
Merge pull request #10906 from pauloscustodio/master
Add Python solutions
Diffstat (limited to 'challenge-074/paulo-custodio/python/ch-1.py')
| -rw-r--r-- | challenge-074/paulo-custodio/python/ch-1.py | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/challenge-074/paulo-custodio/python/ch-1.py b/challenge-074/paulo-custodio/python/ch-1.py new file mode 100644 index 0000000000..cce27f69b9 --- /dev/null +++ b/challenge-074/paulo-custodio/python/ch-1.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 + +# Challenge 074 +# +# TASK #1 > Majority Element +# Submitted by: Mohammad S Anwar +# You are given an array of integers of size $N. +# +# Write a script to find the majority element. If none found then print -1. +# +# Majority element in the list is the one that appears more than +# floor(size_of_list/2). +# +# Example 1 +# Input: @A = (1, 2, 2, 3, 2, 4, 2) +# Output: 2, as 2 appears 4 times in the list which is more than floor(7/2). +# +# Example 2 +# Input: @A = (1, 3, 1, 2, 4, 5) +# Output: -1 as none of the elements appears more than floor(6/2). + +import sys + +def majority_elem(a): + # count instances of each element, get max + count = {} + max_count = 0 + max_elem = None + for x in a: + if x in count: + count[x] += 1 + else: + count[x] = 1 + + if count[x] > max_count: + max_count, max_elem = count[x], x + + # check if majority + if max_count > int(len(a)/2): + return max_elem + else: + return -1 + +a = [int(x) for x in sys.argv[1:]] +print(majority_elem(a)) |
