Home > Mobile >  Parse two strings right to left using a for-loop
Parse two strings right to left using a for-loop

Time:12-05

I can't seem to understand the instruction with the for loop. I am pretty confident the rest of the code is right. Thanks in advance.


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

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

What I get when I run the code. '3' '7' '5' after that I get an error

" Traceback (most recent call last): File "", line 57, in File "", line 27, in decsum IndexError: string index out of range"

what I should get '5' '61' '201' '100001'

CodePudding user response:

You're making A or B equal to '0' when their sizes are unequal (I think you probably wanted to add 0 as padding there).

# Make the text strings A, B equally long:
if len(B) < len(A):
    B = '0'
else:
    A = '0'

I would suggest something like this,

if len(B) < len(A):
    B = '0'*(len(A) - len(B))   B
else:
    A = '0'*(len(B) - len(A))   A

Otherwise, if you want to just iterate for the length of the smaller one I suggest

le = min(len(A), len(B))

CodePudding user response:

def decsum(A, B):
A, B = str(A), str(B)
lnA, lnB = len(A), len(B)
diff = abs(lnA-lnB)
s = ""
for x in range(diff): s = s   '0'  
if(lnA < lnB):      # This is the right way to add 0's in front and make them equally long.
    A = s   A
elif(lnA > lnB):
    B = s   B

# 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 = int(A[-1-i])           # You could have used the type Conversion here

    # Convert B[-1-i] to a single-digit integer named digit2:
    digit2 = int(B[-1-i])           # You could have used the type Conversion here

    # 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

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



Output Now:
'5'
'61'
'201'
'100001'
  • Related