1 回答
TA贡献2037条经验 获得超6个赞
我们可以为此使用列表理解:
def bin_divby(dec, leng):
bn = bin(dec)[:1:-1]
return [bn[i:i+leng][::-1] for i in range(0, len(bn), leng)][::-1]
我们可以通过反转range(..)对象来稍微提高效率:
def bin_divby(dec, leng):
bn = bin(dec)[:1:-1]
n = len(bn) - 1
return [bn[i:i+leng][::-1] for i in range(n - n%leng, -leng, -leng)]
所以这里我们首先反向获取二进制字符串,然后我们迭代该字符串,并且每次对字符串进行切片。最终的结果是相反的。
这产生了预期的:
>>> bin_divby(0b1001011000, 1)
['1', '0', '0', '1', '0', '1', '1', '0', '0', '0']
>>> bin_divby(0b1001011000, 2)
['10', '01', '01', '10', '00']
>>> bin_divby(0b1001011000, 3)
['1', '001', '011', '000']
>>> bin_divby(0b1001011000, 4)
['10', '0101', '1000']
>>> bin_divby(0b1001011000, 5)
['10010', '11000']
>>> bin_divby(0b1001011000, 6)
['1001', '011000']
>>> bin_divby(0b1001011000, 7)
['100', '1011000']
添加回答
举报