我必须解决这个练习:
您能否实现将两个关联向量(在 Python 中表示二进制列表)作为参数并返回两者的补码的函数 AND?
es AND(1100,1110) = 1100
所以我有这种情况:
def AND(vector_a, vector_b):
# insert your code here
# these tests should return True if your code is correct
print(AND([1, 1, 0, 0], [1, 1, 1, 0]) == [1, 1, 0, 0])
print(AND([1, 0, 0, 1, 0, 0, 1], [1, 1, 1, 0, 1, 0, 1]) == [1, 0, 0, 0, 0, 0, 1])
我的解决方案是这样的:
def AND(va,vb):
lista = []
i = 0
while i<len(va):
if va[i] == 1 and vb[i]==1:
lista.append(1)
else:
lista.append(0)
i += 1
return lista
这似乎可行,但现在对于下一个练习我遇到了一些问题:
重写函数 AND 以允许它采用任意数量的入射向量。
def AND(*vectors):
# insert your code here
# these tests should return True if your code is correct
print(AND([1, 1, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0]) == [1, 0, 0, 0])
print(AND([1, 1, 1, 0, 1], [1, 0, 0, 1, 0], [0, 1, 1, 0, 1]) == [0, 0, 0, 0, 0])
你能帮我解决这个问题吗?谢谢
请您参考如下方法:
以下是您可以概括到目前为止所做的事情的方法:
def AND(*vectors):
lista = []
i = 0
while i<len(vectors[0]):
# add a temporary variable to check
# if all i elements are ones
all_ones = True
for v in vectors:
all_ones = all_ones and v[i] == 1
if all_ones:
lista.append(1)
else:
lista.append(0)
i += 1
return lista
