[Tutor] Python Help with Program

Alan Gauld alan.gauld at btinternet.com
Mon Feb 16 09:24:01 CET 2015


On 16/02/15 01:26, 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.
>
> This is what I have:
>
> n1 = int(raw_input('Number #1: '))
> n2 = int(raw_input('Number #2: '))
> add = n1 + n2
 > print ' '
 > print n1, '+', n2, '=', add

Down to here everything is ok and you get the sum of the two numbers


> sn1 = str(n1)
> sn2 = str(n2)
> num1 = 1
> num2 = 1
> num1 == num2

This line doesn't do anything.

> last_n1 = sn1[-num1]
> last_n2 = sn2[-num2]
> int_lastn1 = int(last_n1)
> int_lastn2 = int(last_n2)
> eq = int_lastn1 + int_lastn2
> carry = 0

Before entering the loop you have (for your example)
sn1 = '239', sn2 = '123' num1 = 1, num2 = 1
last_n1 = '9',last_n2 = '3', int_lastn1 = 9, int_lastn2 = 3
eq = 12
carry = 0

> while eq >= 10 and carry < len(sn1) and carry < len(sn2):
>      num1 += 1
>      num2 += 1
>      carry += 1

Your loop only changes num1, num2 and carry.
But only carry is tested in the loop condition.
So in effect you just keep adding 1 to carry
until it is > then len(sn1 or len(sn2), ie 3.

You are not changing anything else, so you are effectively
just counting the number of characters in your shortest
number.

> When I input 239 & 123 as my two numbers it equals 362, which is correct.
> But it says I have 3 carries, when the answer should be 1 carry operation.

You need to completely redesign your algorithm.
Try writing it out using pen and paper to figure
out how you would do it manually.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list