字符串十进制整数相加函数运行异常,循环逻辑理解存疑求助
字符串正整数相加函数decsum的问题排查
问题说明
我编写了用于实现字符串表示的正十进制整数相加的decsum函数,自认除循环相关逻辑外其余代码正确,但运行后输出结果与预期不符,还触发了IndexError: string index out of range错误,请求协助排查问题并理解循环指令。
错误代码
def decsum(A, B): """Adds positive decimal integers A, B represented as text strings""" # Make the text strings A, B equally long: if len(B) < len(A): B = '0' else: A = '0' # Calculate the length of A and store in a new variable named le: le = len(A) # Create a new text string named result, initially empty: result = '' # Create a new variable named carry and initialize it with zero: carry = 0 # Parse A and B right to left using a for-loop with le cycles: for i in range(le): # Convert A[-1-i] to a single-digit integer named digit1: digit1 = single_digit(A[-1-i]) # Convert B[-1-i] to a single-digit integer named digit2: digit2 = single_digit(B[-1-i]) # Add digit1, digit2 and the carry. Store the outcome in sum12: sum12 = digit1 + digit2 + carry # If sum12 is greater than or equal to 10, make the carry 1, and subtract 10 from sum12: if sum12 >= 10: carry = 1 sum12 -= 10 # Otherwise make the carry 0: else: carry = 0 # Convert the single-digit integer sum12 into a one-character text string s12: s12 = str(sum12) # Insert s12 at the beginning of the text string result: result = s12 + result # If the carry is 1 at the end, insert one extra '1' at the beginning of the text string result: if carry == 1: result = '1' + result # Return the result: return result # 假设single_digit函数实现如下(原代码未给出) def single_digit(c): return int(c) # Main program (do not change): print(repr(decsum('2', '3'))) print(repr(decsum('4', '57'))) print(repr(decsum('66', '135'))) print(repr(decsum('99999', '2')))
实际输出与报错
'3' '7' '5' Traceback (most recent call last): File "", line 57, in File "", line 27, in decsum IndexError: string index out of range
预期输出
'5' '61' '201' '100001'
问题排查与修复
1. 核心错误:补零逻辑完全错误
原代码中,当两个字符串长度不等时,直接把较短的字符串替换成单个'0',而不是补零到与较长字符串长度一致:
- 比如输入
decsum('4', '57'),len(B)=2 > len(A)=1,所以A被设置为'0',此时le=1,循环仅执行1次,只计算了个位的0+7,得到'7',完全忽略了十位的5。 - 输入
decsum('99999', '2')时,len(B)=1 < len(A)=5,B被设置为'0',此时le=5,循环执行5次:i=0时取B[-1]没问题,但i=1时取B[-2],而B长度仅为1,索引超出范围,触发IndexError。
修复补零逻辑:使用字符串的zfill方法,给较短的字符串前面补零,直到两者长度相同:
# 替换原补零代码段 max_len = max(len(A), len(B)) A = A.zfill(max_len) B = B.zfill(max_len) le = len(A) # 此时le等于max_len
2. 循环逻辑说明
循环for i in range(le)的作用是从右到左逐位遍历两个字符串:
i从0到le-1递增,A[-1-i]表示:- i=0 → A[-1]:字符串最后一位(个位)
- i=1 → A[-2]:倒数第二位(十位)
- ...以此类推,实现手工加法中从低位到高位的计算顺序。
- 每次循环计算当前位的和(包含进位),更新进位,并将当前位的结果插入到结果字符串的开头(因为我们是从低位往高位算,结果需要反过来拼接)。
修复后完整代码
def decsum(A, B): """Adds positive decimal integers A, B represented as text strings""" # 补零使两个字符串长度一致 max_len = max(len(A), len(B)) A = A.zfill(max_len) B = B.zfill(max_len) le = len(A) result = '' carry = 0 # 从右到左逐位相加 for i in range(le): digit1 = int(A[-1-i]) # 假设single_digit就是转int,直接替换更简洁 digit2 = int(B[-1-i]) sum12 = digit1 + digit2 + carry if sum12 >= 10: carry = 1 sum12 -= 10 else: carry = 0 s12 = str(sum12) result = s12 + result if carry == 1: result = '1' + result return result # 测试程序 print(repr(decsum('2', '3'))) # '5' print(repr(decsum('4', '57'))) # '61' print(repr(decsum('66', '135'))) # '201' print(repr(decsum('99999', '2')))# '100001'
内容的提问来源于stack exchange,提问作者benjinator
相关产品推荐
相关产品推荐

