减去两个递归元组

2024-09-28 20:46:24 发布

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

我在写一个任意精度的计算器,我想写一个减去两个嵌套元组的函数。你知道吗

元组表示为: 对于数字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)

Tags: the函数defresult元组item1list2item2
1条回答
网友
1楼 · 发布于 2024-09-28 20:46:24

这就是你需要的吗?你知道吗

toRecursiveList将数字转换为元组中的元组。。。你知道吗

recursiveSubstract递归地减去每个数字,当遇到负数时,最终保留一个单位。你知道吗

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

substract是使用两个数字进行减法的方法,它将用零填充最微小的数字,因此现在的数字大小相同。你知道吗

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))

相关问题 更多 >