开发者

python recursively convert decimal to hex

开发者 https://www.devze.com 2023-02-28 05:22 出处:网络
How would you recursively or iteratively change a decimal to hexadecimal? I wrote a sample program that does not really work:

How would you recursively or iteratively change a decimal to hexadecimal?

I wrote a sample program that does not really work:

def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print(n)
    else:
        ChangeHex(n / 16)
        if (n == 15):
            print("F")
        if (n == 14):
            print("E")
        if (n == 13):
            print("D")
        if (n == 12):
            print("C"开发者_JAVA技巧)
        if (n == 11):
            print("B")
        if (n == 10):
            print("A")
        n % 16

How would I make it work properly? I know there is a built in function but I want to do it this way.


# Converts a decimal number to hexadecimal.
# Executes a zero-fill for up to six digits.
# This is used for correct conversion back
# to the instruction format. See zero_fill().
# @param  dec  Decimal representation of instruction
# @return  Zero-filled hexadecimal instruction.
def convert(dec):
# BEGIN convert()
    hex = "%X" % dec
    return zero_fill(hex, 6)
# END convert()

# Prepends zeros until the specified
# length is reached. Works recursively.
# @param  n  Number to fill
# @param  length  Length to reach
# @return  Zero-filled number
def zero_fill(n, length):
# BEGIN zero_fill()
    # Check if length requirement is met
    if len(n) != length:
        # Requirement not met, run function again with
        # n having one prepended zero.
        return zero_fill('0'+n, length)
    else:
        # Requirement met, return n.
        return n
# END zero_fill()


The main reason your program is not "working" is because you're misusing functions and immutable objects. Numbers objects are immutable, which means that you can't change the value of a number object in Python, you need to return a new number. And when you're doing ChangeHex(n), you passing the value of n (i.e. the number object) to the function - it doesn't know that there is a variable that was associated with this number. And thus, when you change a local variable like n, the the variable in the caller doesn't change.

You'd like the function to return a new value, not to try to change the one that's passed (which is not really possible). Look up the return statement, and use the value of ChangeHex(n). Hints:

result += ChangeHex(n)


return result

Probably you want to return what you're printing, but I can't really tell.

The same applies to operations. Since the numbers are immutable, an operations on numbers can't change the number, and you need to assign the number to a variable. n % 16 does nothing, you need assignment, like n = n % 16 or n %= 16.

0

精彩评论

暂无评论...
验证码 换一张
取 消