Skip to content

Instantly share code, notes, and snippets.

@buggysolid
Created August 7, 2022 08:59
Show Gist options
  • Save buggysolid/87a234c85fd68a26089e9b85deb1743c to your computer and use it in GitHub Desktop.
Save buggysolid/87a234c85fd68a26089e9b85deb1743c to your computer and use it in GitHub Desktop.
PyBytes 278
"""
You are given a list of integers. Write code to find the majority and minorty numbers in that list.
Definition: a majority number is the one appearing most frequently, a minority number appears least frequently.
Here is a simple example how it should work:
>>> numbers = [1, 2, 2, 3, 2, 3]
>>> major_n_minor(numbers)
(2, 1)
Note - you can assume that there will be only one of each.
Hint: any built-in library that supports convenient and rapid tallies?
"""
from collections import defaultdict
def count_number_frequency(numbers):
counter = defaultdict(int)
for number in numbers:
counter[number] += 1
return counter
def major_number(counter):
max_ = 0
major = 0
for number, count in counter.items():
if count >= max_:
max_ = count
major = number
return major
def minor_number(counter):
# The number has to appear at least once otherwise it isn't in the list.
min_ = 1
minor = 0
for number, count in counter.items():
if count <= min_:
min_ = count
minor = number
return minor
def main():
numbers = [1, 2, 2, 3, 2, 3]
counter = count_number_frequency(numbers)
minor = minor_number(counter)
major = major_number(counter)
print(f"Major = {major}, minor number {minor}.")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment