[Tutor] Python Help with Program

Mark Lawrence breamoreboy at yahoo.co.uk
Mon Feb 16 09:51:32 CET 2015


On 16/02/2015 08:24, Alan Gauld wrote:
> 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.
>

I'd start this exercise at line 1 and work right the way through the 
code, e.g. why bother doing all the work to get sn1 and sn2?

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list