Home > Blockchain >  How can I create a new list when giving intergers, and have to return hexadecimal
How can I create a new list when giving intergers, and have to return hexadecimal

Time:10-24

Given the following list: list = [2,10,10,10,4,5]

How can I write a function that returns the output: output = 210AA:45

I was working with this code so far, but don't know what else to add so that once a number between 10 and 15 is repeated, return the repeated number in its hexadecimal form as in the output

def int_to_string(data): 
    string = ""
    for i in data: 
        hexadecimal = hex(i)
        string  = hexadecimal[2:]
        string[0] = 15
    return string

CodePudding user response:

Use a list [] instead of a string "" strings are immutable and don't support index lookup and assignment. append the hex val and then edit the first index as you see fit to get your result and retun a joined list with ''.join(#ur_lst)

CodePudding user response:

A dictionary describing the mapping between decimal and hex could add readability.

Remark: don't shadow the name of build-functions, in this case list. See doc for a complete list.

lst = [2,10,10,10,4,5,13,15,0] # <- new testing list

# dictionary for conversion
num2hex = {i: str(i) for i in range(10)}
num2hex.update(zip(range(10, 16), "ABCDEF")) 

# conversion list -> str
res = ''
consecutve_hex, is_last_hex = 0, False
for d in lst:
    if 10 <= d <= 15:
        consecutive_hex  = 1
        is_last_hex = False
        if consecutive_hex > 1:
            res  = num2hex[d]
        else:
            res  = str(d)
    else:
        if not is_last_hex:
            if res:
                res  = ':'
        consecutive_hex = 0 
        is_last_hex = True
        res  = str(d)

print(res)
#210AA:4513F:0
  • Related