Skip to content

十进制转任意进制与 yield

  发布于2022-08-18 00:10
保质期2025-08
新鲜度
19%

过程描述

用除N求余法计算3500266221对应的十六进制的过程如下:

3500266221÷16=21876663813218766638÷16=136729141413672914÷16=8545572854557÷16=534091353409÷16=333813338÷16=20810208÷16=13013÷16=013

余数倒序组成数列 [13, 0, 10, 1, 13, 2, 14, 13],按顺序查询进制对应的字符集,得到结果 D0A1D2ED

0123456789101112131415
0123456789ABCDEF
13D
00
10A
11
13D
22
14E
13D

循环实现

python
def dec2n(x, charset):
    base = len(charset)
    result = ''
    quotient = x  # 商
    while quotient >= base:
        # 同时计算商和余数,并存起来:
        quotient, remainder = quotient // base, quotient % base
        result += charset[remainder]
    else:
        result += charset[quotient]
    return result[::-1]

if __name__ == '__main__':
    print(dec2n(3500266221, '0123456789ABCDEF'))
    # 输出:D0A1D2ED

递归实现

python
def dec2n(x, base, charset):
    if x < base:
        return charset[x]
    return dec2n(x // base, base, charset) + charset[x % base]

if __name__ == '__main__':
    BASE16 = '0123456789ABCDEF'
    print(dec2n(3500266221, len(BASE16), BASE16))
    # 输出:D0A1D2ED

迭代器实现

python
def dec2n(x, charset):
    # i=3500266221, base=16, charset="0123456789ABCDEF"
    # -> [13, 14, 2, 13, 1, 10, 0, 13]
    # -> ['D', 'E', '2', 'D', '1', 'A', '0', 'D']
    def dec2seq(i, base):
        while i >= base:
            yield charset[i % base]
            i //= base
        yield charset[i]

    # x=3500266221, charset="0123456789ABCDEF"
    # -> ['D', 'E', '2', 'D', '1', 'A', '0', 'D']
    # -> "DE2D1A0D"
    # -> "D0A1D2ED"
    return ''.join(dec2seq(int(x), len(charset)))[::-1]


if __name__ == '__main__':
    print(dec2n(3500266221, '0123456789ABCDEF'))
    # 输出:D0A1D2ED

yield 只在生成器函数内使用。不同于 return 的一旦返回则立即结束,yield 可以多次返回不同的值,直到函数执行结束。