简体   繁体   中英

Why does if loop is not working on this python program?

while adding two numbers, I want to check how many times carry is occurring – for eg: Input Num 1: 451 Num 2: 349 Output 2 Explanation:

Adding 'num 1' and 'num 2' right-to-left results in 2 carries since ( 1+9) is 10. 1 is carried and (5+4=1) is 10, again 1 is carried. Hence 2 is returned.

def NumberOfCarries(num1, num2):
    count = 0
    l = str(num1)
    i = 0
    if i <= len(l):
        n = num1 % 10
        n2 = num2 % 10
        sum = n + n2
        print(f" num is {num1} and {num2} n1 is {n} and n2 is {n2} and sum is {sum}")
        if sum > 9:
            count += 1
            num1 = num1 // 10
            num2 = num2 // 10
            i += 1
        else:
            num1 = num1 // 10
            num2 = num2 // 10
            i += 1

        return count


num1 = int(input("> "))
num2 = int(input("> "))
print(NumberOfCarries(num1, num2))

Here loop is not working, only one time the sum is generating. I want to generate for each number in numb1. I tired with while, if and for. Please help me.I am new to this

I think you tried to do this:

def number_of_carries(num1, num2):
    amplitude_num1 = len(str(num1))
    amplitude_num2 = len(str(num2))
    count = 0
    i = 0
    carry_over = 0
    while i < amplitude_num1 or i < amplitude_num2:
        n = num1 % 10
        n2 = num2 % 10
        sum_of_digits = n + n2 + carry_over
        print(f" num is {num1} and {num2}, n1 is {n} and n2 is {n2}, carry digit from previous addition is {carry_over}, sum is {sum_of_digits}")
        if sum_of_digits > 9:
            count += 1
            carry_over = 1
        else:
            carry_over = 0

        num1 //= 10
        num2 //= 10
        i += 1
    
    return count

num1 = int(input("> "))
num2 = int(input("> "))
print(number_of_carries(num1, num2))

But if you want to have a solution that would accept more that 2 numbers this could be modified to:

def number_of_carries(numbers):
    amplitude = max(len(str(x)) for x in numbers)
    count = 0
    i = 0
    carry_over = 0
    for i in range(amplitude):
        current_numbers = tuple(x % 10 for x in numbers)
        sum_of_digits = sum(current_numbers) + carry_over
        print(
            f" numbers are {' '.join(str(x) for x in numbers)}, "
            f"current_numbers are {' '.join(str(x) for x in current_numbers)}, "
            f"carry digit from previous addition is {carry_over}, sum is {sum_of_digits}"
        )
        if sum_of_digits > 9:
            count += 1

        carry_over = sum_of_digits // 10
        numbers = tuple(x // 10 for x in numbers)
    
    return count

input_numbers = (198, 2583, 35)
print(number_of_carries(input_numbers))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM