Python3 – Hex cipher

Intro/Explanation

I am beginning with learning Python3 or I am an actual false beginner. Today I am trying to solve relatively easy task from Codewars. First thing which came to my mind was “This is a typical recursion”

Codewars

Source: Codewars

In order to bamboozle your friends, you decide to encode your communications in hexadecimal, using an ASCII to hexadecimal table. At first, none of them can understand your messages. But quickly enough, one of your cleverer friends uncovers your trick and starts sending messages in hexadecimal himself. To stay one (or shall we say, n) step(s) ahead of your friend, you decide to go one step further : you’ll apply the ASCII to hexadecimal conversion more than once.

Your Task

Implement methods encode and decode of class HexCipher, as described above.

Provided to you is a dictionary, TEXT2HEX, mapping ASCII characters to their corresponding hexadecimal code (which will always be 2 digits). For example, TEXT2HEX['a'] evaluates to '61'.

Happy bamboozlin’!

Note: if you get a timeout, just submit it again. If you repeatedly get a timeout, then your code needs some optimization 🙂

Martin’s solution

import binascii
class HexCipher:
    @classmethod
    def encode(cls, s, n):
        return cls.encode((binascii.hexlify(s.encode('ascii')).decode('ascii')), n-1) if n>0 else s

    # Algorithm to encode the string here

    @classmethod
    def decode(cls, s, n):
        return cls.decode(binascii.unhexlify(s).decode('ascii'), n - 1) if n>0 else s

Test cases

test.describe('Sample tests')
test.assert_equals(HexCipher.encode('Hey guys', 0), 'Hey guys')
test.assert_equals(HexCipher.decode('Hey guys', 0), 'Hey guys')
test.assert_equals(HexCipher.encode('Hey guys', 1), '4865792067757973')
test.assert_equals(HexCipher.decode('4865792067757973', 1), 'Hey guys')
test.assert_equals(HexCipher.encode('Hey guys', 2), '34383635373932303637373537393733')
test.assert_equals(HexCipher.decode('34383635373932303637373537393733', 2), 'Hey guys')
test.assert_equals(HexCipher.decode('34383635373932303637373537393733', 1), '4865792067757973')