你能帮我把这个弄好吗?我有一个倒序表中数字的二进制表示。伴随函数bn
可以用来创建编码的数字。你知道吗
我想用进位法加两个二进制数,但我做不好,加上代码越来越乱。限制是在算法上只能使用布尔运算符和列表拼接。你知道吗
# encode binary form of the number, not part of the algo
def bn (n):
return list(reversed(list(map(lambda x: 1 if x == "1" else 0, "{0:b}".format(n)))))
# main algo to sum two binary numbers
def s(m, n):
def _ (a, b, c):
if a and b:
return [0 if (0 if a[0] == b[0] else 1) == c else 1] + \
_(a[1:], b[1:], 1 if (c and (a[0] or b[0])) or (a[0] and b[0]) else 0)
if a:
return [0 if a[0] == c else 1] + ([1]+a[2:] if c else a[1:])
if b:
return [0 if b[0] == c else 1] + ([1]+b[2:] if c else b[1:])
return [1] if c else []
return _(m, n, 0)
print(bn(2017), bn(3), s(bn(2017), bn(3)), bn(2017+3))
这里是s(bn(2017), bn(3))
[0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1]
与bn(2017+3))
不匹配
[0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1]
应该的。你知道吗
因此,我请求帮助纠正代码加上任何优化,你可以做将不胜感激。你知道吗
要测试基本情况,可以使用以下方法:
for i in range(0, 12, 2):
for j in range(0, 12, 3):
x, y = bn(i+j), s(bn(i), bn(j))
print(x == y, bn(i), bn(j), "%s + %s = %s %s -> %s" % (i, j, i+j, x, y))
但要注意,这并没有抓住我上面给出的2017+3问题加法。。。你知道吗
调试帮助:第三次迭代的
c
输入错误。图为第二次迭代结束我的测试用例后来显示空的
a
或b
的代码有缺陷,并且在截图调试c
错误后纠正了这一点。你知道吗修正:
编辑:
您可以简化最后两种情况:
相关问题 更多 >
编程相关推荐