문제 : PrimaryArithmetic
[Recursion]을 이용해보기.
1 import unittest
2
3 def countCarry(a,b, carry=0):
4 if a+b==0:
5 return 0
6 carry = (a%10+b%10+carry) / 10
7 return carry + countCarry(a/10, b/10, carry)
8
9 def countCarryWithTp(a,b, tcarry=0, pcarry=0):
10 if a+b==0:
11 return tcarry
12 pcarry = (a%10+b%10+pcarry) / 10
13 tcarry += pcarry
14 return countCarryWithTp(a/10, b/10, tcarry, pcarry)
15
16 class SomeTest(unittest.TestCase):
17 def testCountCarry(self):
18 self.assertEquals(3, countCarry(1,999))
19 self.assertEquals(1, countCarry(1,889))
20 self.assertEquals(2, countCarry(555,345))
21 def testCountCarry(self):
22 self.assertEquals(3, countCarryWithTp(1,999))
23 self.assertEquals(1, countCarryWithTp(1,889))
24 self.assertEquals(2, countCarryWithTp(555,345))
25
26 if __name__=='__main__':
27 unittest.main()
countCarryWithTp와 같은 형태는 쉽게 나왔으나, countCarry와 같은 형태는 바로 유추되지 않았다. 어떠한 발상의 전환이 필요한 것일까. -- yong27 2006-02-27 19:18:33