back

python workout: exercise 4

hexadecimal output

problem

For this exercise, you need to write a function (hex_output) that takes a hex num- ber and returns the decimal equivalent. That is, if the user enters 50, you’ll assume that it’s a hex number (equal to 0x50) and will print the value 80 to the screen. And no, you shouldn’t convert the number all at once using the int function, although it’s permissible to use int one digit at a time.

attempts

The whole exercise talks about iteration and mentions the exponentiation operator in the tip. So let’s implement hex_output from scratch:

def hex_output(hex_n: str) -> int:
    decimal_n = 0
    power_of_16 = 1
    for digit in reversed(hex_n[2:]):
        decimal_n += power_of_16 * int(digit)
        power_of_16 *= 16
    return decimal_n
print(hex_output(hex(80)))
80

And that works.

But if we want to use the exponentiation operation instead, we can use:

def hex_output(hex_n: str) -> int:
    decimal_n = 0
    for exponent, digit in enumerate(reversed(hex_n[2:])):
        decimal_n += 16**exponent * int(digit)
    return decimal_n
print(hex_output(hex(80)))
80

That’s simpler!

Only problem with our approach is that when we convert digit we might have a letter like ‘A’. So we need to tell int it’s a base 16 number.

So this is the final one:

def hex_output(hex_n: str) -> int:
    decimal_n = 0
    for exponent, digit in enumerate(reversed(hex_n[2:])):
        decimal_n += 16**exponent * int(digit, 16)
    return decimal_n
print(hex_output(hex(16)))
16

solution

The book’s implementation:

def hex_output():
    decnum = 0
    hexnum = input('Enter a hex number to convert: ')
    for power, digit in enumerate(reversed(hexnum)):
        decnum += int(digit, 16) * (16 ** power)
        print(decnum)
hex_output()

They also take user input directly instead of an argument.

beyond the exercise

using ord and chr functions

  • problem

    Reimplement the solution for this exercise such that it doesn’t use the int function at all, but rather uses the built-in ord and chr functions to identify the character. This implementation should be more robust, ignoring characters that aren’t legal for the entered number base.

  • attempts

    Let’s take the book’s solution as a base for extension:

    def hex_output():
        decnum = 0
        hexnum = input('Enter a hex number to convert: ')
        for power, digit in enumerate(reversed(hexnum)):
            digit = ord(digit)
            if 47 <= digit <= 58:
                digit = digit - 47
            elif 65 <= digit <= 70:
                # add the 10 back because 'A' has dec val 10
                digit = digit - 65 + 10
            else:
                raise ValueError(f"Inputed hex number contains invalid characters: {hexnum}")
            decnum += digit * (16**power)
        return decnum
    

name triangle

  • problem

    Write a program that asks the user for their name and then produces a “name triangle”: the first letter of their name, then the first two letters, then the first three, and so forth, until the entire name is written on the final line.

  • attempts

    We’ll just implement as a function with an argument instead of one that takes user input via input:

    def name_triangle(name: str):
        for i in range(len(name)):
            print(name[:i+1])
    name_triangle('Jonah')
    
mail@jonahv.com