13

この関数は、パラメーターとして整数を受け取り、ビットのリストとしてバイナリで表された同じ値を表すリストを返す必要があります。リストの最初の要素が最上位 (左端) ビットです。

私の関数は現在'1011'、数字の 11 を出力していますが、[1,0,1,1]代わりに必要です。

例えば、

>>> convert_to_binary(11)
[1,0,1,1]
4

15 に答える 15

16
def trans(x):
    if x == 0: return [0]
    bit = []
    while x:
        bit.append(x % 2)
        x >>= 1
    return bit[::-1]
于 2012-11-23T03:39:28.140 に答える
12

楽しみのために-再帰的なワンライナーとしてのソリューション:

def tobin(x):
    return tobin(x/2) + [x%2] if x > 1 else [x]
于 2012-11-23T04:05:58.400 に答える
0

Pythonic の方法ではありませんが、それでも動作します:

def get_binary_list_from_decimal(integer, bits):
    '''Return a list of 0's and 1's representing a decimal type integer.

    Keyword arguments:
    integer -- decimal type number.
    bits -- number of bits to represent the integer.

    Usage example:
    #Convert 3 to a binary list
    get_binary_list_from_decimal(3, 4)
    #Return will be [0, 0, 1, 1]
    '''
    #Validate bits parameter.
    if 2**bits <= integer:
        raise ValueError("Error: Number of bits is not sufficient to \
                          represent the integer. Increase bits parameter.")

    #Initialise binary list
    binary_list = []
    remainder = integer
    for i in range(bits-1, -1, -1):
        #If current bit value is less than or equal to the remainder of 
        #the integer then bit value is 1.
        if 2**i <= remainder:
            binary_list.append(1)
            #Subtract the current bit value from the integer.
            remainder = remainder - 2**i
        else:
            binary_list.append(0)

    return binary_list

使用方法の例:

get_binary_list_from_decimal(1, 3)
#Return will be [0, 0, 1]
于 2016-08-31T22:29:57.543 に答える
0

これでできます。ビルトインがある場合、独自の関数をローリングしても意味がありません。

def binary(x):
    return [int(i) for i in bin(x)[2:]]

このbin()関数はバイナリの文字列に変換します。ストリップし0bてセット完了です。

于 2012-11-23T03:41:47.857 に答える
0

実際には最も効率的ではありませんが、少なくともそれを理解するための簡単な概念的な方法を提供します...

1) 1 になるまで、すべての数字を 2 で割ります。

2) 逆の順序で、この数値配列のビットを作成し、偶数の場合は 0 を追加し、奇数の場合は 1 を追加します。

その文字通りの実装は次のとおりです。

def intToBin(n):
    nums = [n]
    while n > 1:
        n = n // 2
        nums.append(n)

    bits = []
    for i in nums:
        bits.append(str(0 if i%2 == 0 else 1))
    bits.reverse()
    print ''.join(bits)

メモリをより有効に利用するバージョンは次のとおりです。

def intToBin(n):
    bits = []

    bits.append(str(0 if n%2 == 0 else 1))
    while n > 1:
        n = n // 2
        bits.append(str(0 if n%2 == 0 else 1))

    bits.reverse()
    return ''.join(bits)
于 2016-04-17T18:31:49.393 に答える