Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition carries in Python

number1 = int(input('Number #1: '))
number2 = int(input('Number #2: '))
l = len(str(number1))
l1 = len(str(number2))
print()

def addition():
    print(' ',max(number1,number2))
    print('+')
    print(' ',min(number1,number2))
    print('-'*(max(l,l1)+2))
    print('  ')
    print(' ',number1+number2)

def carries():
    while (int(str(number1)[::-1])+int(str(number2)[::-1]))>=10:
        carries = 0
        carries = carries + 1     
        return carries

addition()


print()
print('Carries : ',carries())

I am trying to make a program that does the addition of two user input numbers and calculates the answer while also stating how many carries there are. Carries being if 9+8=17, then there would be 1 carry and so forth. I am having issues with having my program go beyond 1 carry. So this program so far is only applicable for user input numbers that when added are below 99. If you could explain to me how I would go about altering this program to make it applicable to any numbers, that would be great. I was thinking about using the len(number1) and len(number2) and then inputting the string of the user input backwards so it would look like str(number1[::-1])) but I do not think it works like that.

like image 850
CoTaNgO Avatar asked Mar 17 '26 08:03

CoTaNgO


1 Answers

Fun one-liner solution

def numberOfCarryOperations(a, b):
    f=lambda n:sum(map(int,str(n)));return(f(a)+f(b)-f(a+b))/9

# f is the digitSum function :)

Explanation

Asserting a,b >=0, you can proof mathematically: every time you have a carry, the digitSum decreases by 9.

9, because we are in number system 10, so we "lose 10" on one digit if we have carry, and we gain +1 as the carry.

Readable solution

def digitSum(n):
    return sum(map(int,str(n)))

def numberOfCarryOperations(a, b)
    # assert(a >= 0); assert(b >= 0);
    return (digitSum(a) + digitSum(b) - digitSum(a+b)) / 9
like image 164
PEZO Avatar answered Mar 19 '26 20:03

PEZO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!