🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of n0mn0m

n0mn0m's solution

to Perfect Numbers in the Python Track

Published at Jan 29 2021 · 0 comments
Instructions
Test suite
Solution

Determine if a number is perfect, abundant, or deficient based on Nicomachus' (60 - 120 CE) classification scheme for natural numbers.

The Greek mathematician Nicomachus devised a classification scheme for natural numbers, identifying each as belonging uniquely to the categories of perfect, abundant, or deficient based on their aliquot sum. The aliquot sum is defined as the sum of the factors of a number not including the number itself. For example, the aliquot sum of 15 is (1 + 3 + 5) = 9

  • Perfect: aliquot sum = number
    • 6 is a perfect number because (1 + 2 + 3) = 6
    • 28 is a perfect number because (1 + 2 + 4 + 7 + 14) = 28
  • Abundant: aliquot sum > number
    • 12 is an abundant number because (1 + 2 + 3 + 4 + 6) = 16
    • 24 is an abundant number because (1 + 2 + 3 + 4 + 6 + 8 + 12) = 36
  • Deficient: aliquot sum < number
    • 8 is a deficient number because (1 + 2 + 4) = 7
    • Prime numbers are deficient

Implement a way to determine whether a given number is perfect. Depending on your language track, you may also need to implement a way to determine whether a given number is abundant or deficient.

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run pytest perfect_numbers_test.py

Alternatively, you can tell Python to run the pytest module: python -m pytest perfect_numbers_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/perfect-numbers directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see Running the Tests.

Source

Taken from Chapter 2 of Functional Thinking by Neal Ford. http://shop.oreilly.com/product/0636920029687.do

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

perfect_numbers_test.py

import unittest

from perfect_numbers import classify

# Tests adapted from `problem-specifications//canonical-data.json`


class PerfectNumbersTest(unittest.TestCase):
    def test_smallest_perfect_number_is_classified_correctly(self):
        self.assertIs(classify(6), "perfect")

    def test_medium_perfect_number_is_classified_correctly(self):
        self.assertIs(classify(28), "perfect")

    def test_large_perfect_number_is_classified_correctly(self):
        self.assertIs(classify(33550336), "perfect")


class AbundantNumbersTest(unittest.TestCase):
    def test_smallest_abundant_number_is_classified_correctly(self):
        self.assertIs(classify(12), "abundant")

    def test_medium_abundant_number_is_classified_correctly(self):
        self.assertIs(classify(30), "abundant")

    def test_large_abundant_number_is_classified_correctly(self):
        self.assertIs(classify(33550335), "abundant")


class DeficientNumbersTest(unittest.TestCase):
    def test_smallest_prime_deficient_number_is_classified_correctly(self):
        self.assertIs(classify(2), "deficient")

    def test_smallest_non_prime_deficient_number_is_classified_correctly(self):
        self.assertIs(classify(4), "deficient")

    def test_medium_deficient_number_is_classified_correctly(self):
        self.assertIs(classify(32), "deficient")

    def test_large_deficient_number_is_classified_correctly(self):
        self.assertIs(classify(33550337), "deficient")

    def test_edge_case_no_factors_other_than_itself_is_classified_correctly(self):
        self.assertIs(classify(1), "deficient")


class InvalidInputsTest(unittest.TestCase):
    def test_zero_is_rejected_as_it_is_not_a_positive_integer(self):
        with self.assertRaisesWithMessage(ValueError):
            classify(0)

    def test_negative_integer_is_rejected_as_it_is_not_a_positive_integer(self):
        with self.assertRaisesWithMessage(ValueError):
            classify(-1)

    # Utility functions
    def assertRaisesWithMessage(self, exception):
        return self.assertRaisesRegex(exception, r".+")


if __name__ == "__main__":
    unittest.main()
import math


def factor(n):
    for i in range(2, math.ceil(math.sqrt(n))):
        if n % i == 0:
            yield i
            if i * i != n:
                yield n // i


def classify(number):
    if number < 1:
        raise ValueError("Classification is only possible with positive values")

    aliquot = sum(factor(number)) + 1

    if aliquot < number or number == 1:
        return "deficient"
    elif aliquot == number:
        return "perfect"
    elif aliquot > number:
        return "abundant"
    else:
        raise ValueError(f"Classification failed for {number}")

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?