减去两个递归元组

时间:2017-01-13 12:22:46

标签: python python-3.x

我正在编写一个任意精度计算器,我正在编写一个减去两个嵌套元组的函数。

元组表示为: 对于数字12345,元组将看起来像(1,(2,(3,(4,(5, ())))))

这是我的功能。它使用一个函数返回具有较大值和效用函数的元组来访问成员并查找元组的长度。

def subtractLists(list1, list2):
    borrow = 0
    result = ()
    larger = findLargerValue(list1,list2)
    smaller = list2 if larger != list2 else list1
    index1 = len_rlist(larger)-1
    index2 = len_rlist(smaller)-1
    nonzero = 0
    while index1 >= 0 and index2 >= 0:
        item1 = getitem_rlist(larger, index1)
        item2 = getitem_rlist(smaller, index2)


        if index1 == nonzero:
            borrow = 0
            item1 -= 1
        if item1 >= item2:
            result = makeRlist(borrow + item1 - item2, result)
            index1 -= 1
            index2 -= 1
        else:
            newindex = index1-1
            while getitem_rlist(larger, newindex) == 0 and newindex >= 0:
                newindex -= 1
            nonzero = newindex
            result = makeRlist(10 + item1 - item2)
            borrow = 9
            index1 -= 1
            index2 -= 1

    return result

如果我在表示数字12345和999的列表上应用此函数,则输出为:

12345-999 = (6,None)

此处makeRlist

def first(s):
    """Return the first member of the recursive list"""
    return s[0]
def rest(s):
    """Return the second member, which is the rest of the recursive list"""
    return s[1]
def makeRlist(first,rest=None):
    """Create a recursive list"""
    return (first,rest)

1 个答案:

答案 0 :(得分:0)

这就是你需要的吗?

toRecursiveList将数字转换为元组中元组中的元组...

recursiveSubstract递归地减去每个数字,并在遇到负数时最终保留一个单位。

getDepth返回元组的深度(数字的长度)

substract是您使用两个数字进行减法调用的方法,它将使用零填充tinyest,因此现在的数字具有相同的大小。

def toRecursiveList(n, i = 0):
  return (int(str(n)[i]), toRecursiveList(n, i + 1)) if i < len(str(n)) else ()

def recursiveSubstract(l1, l2):
  tuple, toRet = (), 0
  if l1 != () and l2 != ():
    sub = l1[0] - l2[0]
    if l1[0] - l2[0] < 0: sub, toRet = sub + 10, 1
    next, ret = recursiveSubstract(l1[1], l2[1])
    tuple = (sub - ret, next)
  return tuple, toRet

def getDepth(l, i = 1):
  return getDepth(l[1], i + 1) if l[1] != () else i

def substract(n1, n2):
  l1, l2 = toRecursiveList(max(n1, n2)), toRecursiveList(min(n1, n2))
  while getDepth(l1) > getDepth(l2): l2 = (0, l2)
  return recursiveSubstract(l1, l2)[0]

print(substract(12345, 999))