[Tutor] Python Help with Program

Steven D'Aprano steve at pearwood.info
Mon Feb 16 13:17:22 CET 2015


Hi Tina, or Taylor, welcome!

Sorry but your email "From" header says your name is Tina and your 
signature says Taylor so I'm not sure which name you prefer.


On Sun, Feb 15, 2015 at 07:26:35PM -0600, Tina Figz wrote:
> I'm having a problem with my program and I'm not sure how to correct it
> (I'm in an intro programming class).
> 
> My program is supposed two numbers and count the number of carry
> operations.

Let's start by working it out using pencil and paper. Write down two 
numbers, lined up on the right:

472837
 29152


for example. Let's go through and check for carries:

Number of carries so far: 0
7 and 2 = 9, no carry.
3 and 5 = 8, no carry.
8 and 1 = 9, no carry
2 and 9 = 11, carry the 1. Add one to the number of carries.
7 and 2, plus the 1 we carried, = 10, carry the 1. So add one to number 
of carries.
4, plus the 1 we carried, = 5, no carry.

So the number of carries is two.

The process is to take the digits of each number, starting from the 
right-hand end, in pairs. If you run out of digits for one number before 
the other, use 0. Add the two digits together, plus any carry digit from 
before, and if the result is larger than 9, there's a carry.

We start with the number of carries equal to 0, and add 1 to that *only* 
if adding the pair of digits is larger than 9.

Let's see what you have:

[snip part of the code]
> eq = int_lastn1 + int_lastn2
> carry = 0
> while eq >= 10 and carry < len(sn1) and carry < len(sn2):
>     num1 += 1
>     num2 += 1
>     carry += 1

You start on the right track: you check whether the last two digits add 
to more than 9. But, you never check the next two digits, or the two 
after that. You calculate "eq" (which is not a good name, by the way) 
once, outside the loop, but never calculate it again with any additional 
digits.

Instead, you add 1 to carry *every single time*, regardless of the 
digits (apart from the first).

Fun fact: (well, not that fun) you have to repeat the calculation each 
time through the loop, otherwise you're just using the same result over 
and over again. Example:

py> my_string = "12345"
py> position = -1
py> total = int(my_string[position]) + 1000
py> while position > -len(my_string):
...     print(total)
...     position = position - 1
...
1005
1005
1005
1005


The total never changes, because we never re-calculate it. Instead:

py> my_string = "12345"
py> position = -1
py> while position > -len(my_string):
...     total = int(my_string[position]) + 1000
...     print(total)
...     position = position - 1
...
1005
1004
1003
1002


Does that help you see why your code counts the wrong number of carries, 
and help you fix it?



-- 
Steve


More information about the Tutor mailing list