我在写一个任意精度的计算器,我想写一个减去两个嵌套元组的函数。你知道吗
元组表示为:
对于数字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)
这就是你需要的吗?你知道吗
toRecursiveList
将数字转换为元组中的元组。。。你知道吗recursiveSubstract
递归地减去每个数字,当遇到负数时,最终保留一个单位。你知道吗getDepth
返回元组的深度(数字的长度)substract
是使用两个数字进行减法的方法,它将用零填充最微小的数字,因此现在的数字大小相同。你知道吗相关问题 更多 >
编程相关推荐