【问题标题】:Implement increment operation for different basis对不同的基数实施增量操作
【发布时间】:2020-04-24 19:04:28
【问题描述】:

我正在尝试对整数列表实现增量操作,这样

  1. 列表长度为 N
  2. 每个元素都是小于 B 的整数。B 是运算的基础。
  3. 如果我调用该操作,它会将 1 添加到列表的最后一个元素。
  4. 如果超过 B,则继续到下一个元素。

例如,如果列表如下所示,B = 13

list = [0, 0, 0, 5, 12]
increment(list)
print(list) # return [0, 0, 0, 6, 0]

我的实际目标是打印从 [0,0,0,0,0] 到 [12,12,12,12,12] 的所有列表。然而,我在携带数字方面遇到了困难。

【问题讨论】:

  • 你尝试了什么?

标签: python list add


【解决方案1】:

递归代码示例

代码

def increment(lst, base):
  if len(lst) == 0:
    return lst

  lst[-1] += 1  # increment right most digit in list

  if lst[-1] >= base:
    # carry forward
    lst[-1] = 0   # reset right most to zero
                  # (1) increment without right most t
                  # (2) then append right most digit
    lst = increment(lst[:-1], base) + lst[-1:]

  return lst

测试

print('Base 12 example')
lst = [0, 0, 0, 5, 12]
print(lst)
for i in range(10):
  lst = increment(lst, 12)
  print(lst)

print('Base 3 example')
lst = [0, 0, 0]
print(lst)
for i in range(10):
  lst = increment(lst, 3)
  print(lst)

出局

Base 12 example
[0, 0, 0, 5, 12]
[0, 0, 0, 6, 0]
[0, 0, 0, 6, 1]
[0, 0, 0, 6, 2]
[0, 0, 0, 6, 3]
[0, 0, 0, 6, 4]
[0, 0, 0, 6, 5]
[0, 0, 0, 6, 6]
[0, 0, 0, 6, 7]
[0, 0, 0, 6, 8]
[0, 0, 0, 6, 9]
Base 3 example
[0, 0, 0]
[0, 0, 1]
[0, 0, 2]
[0, 1, 0]
[0, 1, 1]
[0, 1, 2]
[0, 2, 0]
[0, 2, 1]
[0, 2, 2]
[1, 0, 0]
[1, 0, 1]

【讨论】:

    猜你喜欢
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多