在python中创建数字的二进制表示矩阵

2024-06-27 02:14:28 发布

您现在位置:Python中文网/ 问答频道 /正文

为了在sage(基于python的编译器)中编程Hamming-cod,我需要创建一个矩阵,其中每列都是一个数字的二进制表示 假设哈明(3)矩阵应该是这样的

0  0  0  1  1  1  1
0  1  1  0  0  1  1
1  0  1  0  1  0  1

它是从1到7的二进制表示。 所以我现在所做的就是把任何给定的数转换成它的二进制表示: 我做了一个小函数,取n和r两个值 在r位上重复n

^{pr2}$

所以现在我想收集所有的信息,把它们放在一个像上面这样的大矩阵中


Tags: 函数信息编译器编程二进制矩阵数字cod
3条回答

您只需将所有这些二进制表示转换为整数列表,将它们收集到一个列表列表中,最后transpose该列表以获得所需的输出。在

n = 3
binary = []
for i in range(1, 2**n):
    s = binrep(i, n)
    binary.append(map(int, s))
matrix = zip(*binary)

或者在一行:matrix = zip(*(map(int, binrep(i, n)) for i in range(1, 2**n)))

结果是

^{pr2}$

还要注意还有其他方法convert numbers to binary,例如使用^{}

def binrep(n,r):
    return "{0:0{1}b}".format(n, r)

就像zoosuck提到的,我建议用bin()函数来替换代码。假设格式相似,按顺序打印:

L = ['10101010', '10101010']

for i in L:
    print ' '.join([j for j in i])

以类似的方式,您可以将其附加到列表或字典中。在

除其他答案外,使用numpy的答案:

import numpy as np

# we're creating the binary representation for all numbers from 0 to N-1
N = 8

# for that, we need a 1xN matrix of all the numbers
a = np.arange(N, dtype=int)[np.newaxis,:]

# we also need a log2(N)x1 matrix, for the powers of 2 on the numbers.
# floor(log(N)) is the largest component that can make up any number up to N
l = int(np.log2(N))
b = np.arange(l, dtype=int)[::-1,np.newaxis]

# This step is a bit complicated, so I'll explain it below.
print np.array(a & 2**b > 0, dtype=int)

打印:

^{pr2}$

线

print np.array(a & 2**b > 0, dtype=int)

同时做一些事情。我将把它分成几个简单的步骤:

# this takes our matrix b and creates a matrix containing the powers of 2
# up to 2^log2(N) == N
# (if N is a power of 2; otherwise, up to the next one below)
powers = 2**b

# now we calculate the bit-wise and (&) for each combination from a and b.
# because a has one row, and b as one column, numpy will automatically
# broadcast all values, so the resulting array has size log2(N)xN.
u = a & powers

# this is almost what we want, but has 4's in the first row,
# 2's in the second row and 1's in the last one.
# one method of getting 1's everywhere is to divide by powers:
print u / powers

# another way is to check where u > 0, which yields an array of bools,
# which we then convert to numbers by turning it into an array of ints.
print np.array(u > 0, dtype=int)

相关问题 更多 >