在Python中用反列表表示的两个二进制数的和

2024-04-23 16:28:27 发布

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

你能帮我把这个弄好吗?我有一个倒序表中数字的二进制表示。伴随函数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问题加法。。。你知道吗


Tags: orandofthe代码returnifdef
1条回答
网友
1楼 · 发布于 2024-04-23 16:28:27

调试帮助:第三次迭代的c输入错误。图为第二次迭代结束

Debugging VS2017

我的测试用例后来显示空的ab的代码有缺陷,并且在截图调试c错误后纠正了这一点。你知道吗

修正:

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]) and not c else 0) # error here
    if a:
      return [0 if a[0] == c else 1] + (_(a[1:],[1],0) if ((a[0] == c) and c) else a[1:]) # error here as well
    if b:
      return [0 if b[0] == c else 1] + (_([1],b[1:],0) if ((b[0] == c) and c) else b[1:]) # error here as well
    return [1] if c else []

  return _(m, n, 0)

# TESTING - till 255 + 255

for a in range(255):
    for b in range(255):
        if( s( bn(a),bn(b) ) == bn(a+b)):
            continue;
        else:
            print("error for a = ",a," and b=",b)
            print(bn(a), " + " , bn(b)," = ", bn(a+b), "    not: ", s( bn(a),bn(b) ))

print ("done")

编辑:

您可以简化最后两种情况:

if a:
  return _(a,[c],0) if c else a 
if b:
  return _(b,[c],0) if c else b 

相关问题 更多 >