Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Hexadecimal in the Python Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Convert a hexadecimal number, represented as a string (e.g. "10af8c"), to its decimal equivalent using first principles (i.e. no, you may not use built-in or external libraries to accomplish the conversion).

On the web we use hexadecimal to represent colors, e.g. green: 008000, teal: 008080, navy: 000080).

The program should handle invalid hexadecimal strings.

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 the appropriate command below (why they are different):

  • Python 2.7: py.test hexadecimal_test.py
  • Python 3.4+: pytest hexadecimal_test.py

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version): python -m pytest hexadecimal_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/hexadecimal 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 the help page.

Source

All of Computer Science http://www.wolframalpha.com/examples/NumberBases.html

Submitting Incomplete Solutions

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

hexadecimal_test.py

# To avoid trivial solutions, try to solve this problem without the
# function int(s, base=16)

import unittest

from hexadecimal import hexa


class HexadecimalTest(unittest.TestCase):
    def test_valid_hexa1(self):
        self.assertEqual(hexa('1'), 1)

    def test_valid_hexa2(self):
        self.assertEqual(hexa('c'), 12)

    def test_valid_hexa3(self):
        self.assertEqual(hexa('10'), 16)

    def test_valid_hexa4(self):
        self.assertEqual(hexa('af'), 175)

    def test_valid_hexa5(self):
        self.assertEqual(hexa('100'), 256)

    def test_valid_hexa6(self):
        self.assertEqual(hexa('19ACE'), 105166)

    def test_valid_hexa7(self):
        self.assertEqual(hexa('000000'), 0)

    def test_valid_hexa8(self):
        self.assertEqual(hexa('ffff00'), 16776960)

    def test_valid_hexa9(self):
        self.assertEqual(hexa('00fff0'), 65520)

    def test_invalid_hexa(self):
        with self.assertRaisesWithMessage(ValueError):
            hexa('carrot')

    # Utility functions
    def setUp(self):
        try:
            self.assertRaisesRegex
        except AttributeError:
            self.assertRaisesRegex = self.assertRaisesRegexp

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


if __name__ == '__main__':
    unittest.main()
class Hexa:
    CHAR_VALUES = {'a': 10,
                   'b': 11,
                   'c': 12,
                   'd': 13,
                   'e': 14,
                   'f': 15}
    VALID_CHARS = set(map(str, range(0, 10)) + CHAR_VALUES.keys())
    BASE = 16

    @classmethod
    def convert(cls, inp):
        if not cls.valid(inp):
            raise ValueError
        return sum([cls.convert_char(char) * cls.BASE**index for index, char in
                    enumerate(reversed(inp))])

    @classmethod
    def valid(cls, inp):
        return set(inp) <= cls.VALID_CHARS

    @classmethod
    def convert_char(cls, char):
        return int(char) if char.isdigit() else cls.CHAR_VALUES[char]


def hexa(inp):
    return Hexa.convert(inp.lower())

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?