Discuss / Python / 是我把问题想复杂了吗....

是我把问题想复杂了吗....

Topic source

diska本尊

#1 Created at ... [Delete] [Delete and Lock User]

我研究了半个多小时才写出来,再一看大家的答案...吐血三升....

def hex_lhf(x): hex_list = [] as_list = ['A', 'B', 'C', 'D', 'E', 'F'] while 1: y = x % 16 x = x // 16 if y > 9: hex_list.append(as_list[y-10]) else: hex_list.append(str(y)) if x == 0: break hex_list.append('0x') hex_list.reverse() a = ''.join(hex_list) return a

print(hex_lhf(255))

你为什么要再造一次已经有了的轮子,造别的轮子不好吗?比如八进制的(滑稽脸)

当冇If

#3 Created at ... [Delete] [Delete and Lock User]

确实整复杂了

###一直默默看着没有回复过,现在把我的答案贴一下,原来回复支持 md

"""十六进制查表法 实际 java 原来学习时候写过"""
def my_hex(num):

    hex_list = []
    # 这里用不可变 tuple 可能会比较好
    t_mt = ('A','B','C','D','E','F')
    while True:
        mod_, num = num %16, num//16
        hex_list.append(t_mt[mod_-10]) if mod_>9 else hex_list.append(str(mod_))
        if num== 0 :
            break
    hex_list.append('0x')
    hex_list.reverse()
    return ''.join(hex_list)
"""八进制"""
def my_octonary(num):
    octonary_list = []
    while True:
        mod_,num = num%8,num//8
        octonary_list.append(str(mod_))
        if num == 0:
            break
    octonary_list.append('0o')
    octonary_list.reverse()
    return ''.join(octonary_list)

my_octonary(9)

  • 1

Reply