Skip to content

Instantly share code, notes, and snippets.

@miau
Created February 25, 2010 23:41
Show Gist options
  • Save miau/315187 to your computer and use it in GitHub Desktop.
Save miau/315187 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import unittest
c = {
0: u'零',
1: u'一',
2: u'二',
3: u'三',
4: u'四',
5: u'五',
6: u'六',
7: u'七',
8: u'八',
9: u'九',
#~ 0: u'U',
#~ 1: u'S',
#~ 2: u'Z',
#~ 3: u'J',
#~ 4: u'C',
#~ 5: u'E',
#~ 6: u'G',
#~ 7: u'R',
#~ 8: u'M',
#~ 9: u'F',
}
# 4 桁ごとの位
k = {
0: u'',
1: u'万',
2: u'億',
3: u'兆',
#~ 0: u'',
#~ 1: u'K',
#~ 2: u'L',
#~ 3: u'X',
}
# 4 桁内の位の表現
k4 = {
0: u'',
1: u'十',
2: u'百',
3: u'千',
#~ 0: u'',
#~ 1: u'Y',
#~ 2: u'H',
#~ 3: u'T',
}
# 与えられた数字を漢数字の表現で返す
def nk(n):
result = u''
n = int(n)
if n == 0:
return c[0]
# 4 桁ごとに区切る
ks = []
while n > 0:
d, m = divmod(n, 10000)
ks += [m]
n = d
# 4 桁ずつ表示する
while len(ks) > 0:
n = ks.pop()
if n == 0:
continue
result = result + ("%s" % nk4(n)) # 4 桁内の表現
result = result + ("%s" % k[len(ks)]) # 万、億、兆
#~ print result.encode('utf-8')
return result
# 4 桁内の位の表現を返す
def nk4(n):
result = ''
# 1 桁ごとに区切る
a = []
while n > 0:
d, m = divmod(n, 10)
a += [m]
n = d
# 4 桁ずつ表示する
while len(a) > 0:
n = a.pop()
if n == 0:
continue
if n != 1 or len(a) == 0:
# 一の位以外では 1 は出力しない
result = result + ("%s" % c[n]) # 一~九
result = result + ("%s" % k4[len(a)]) # 十、百、千
return result
# クラス作らないと unit test できないのかな?
class Nk(unittest.TestCase):
def testNk(self):
self.assertEqual(nk(0), u'零')
self.assertEqual(nk(1), u'一')
self.assertEqual(nk(2), u'二')
self.assertEqual(nk(3), u'三')
self.assertEqual(nk(4), u'四')
self.assertEqual(nk(5), u'五')
self.assertEqual(nk(6), u'六')
self.assertEqual(nk(7), u'七')
self.assertEqual(nk(8), u'八')
self.assertEqual(nk(9), u'九')
self.assertEqual(nk(10000), u'一万')
self.assertEqual(nk(10000 ** 2), u'一億')
self.assertEqual(nk(10000 ** 3), u'一兆')
self.assertEqual(nk(10), u'十')
self.assertEqual(nk(100), u'百')
self.assertEqual(nk(1000), u'千')
self.assertEqual(nk(11), u'十一')
self.assertEqual(nk(12), u'十二')
self.assertEqual(nk(13), u'十三')
self.assertEqual(nk(123), u'百二十三')
self.assertEqual(nk(1234), u'千二百三十四')
self.assertEqual(
nk(1234567890123456),
u'千二百三十四兆五千六百七十八億九千十二万三千四百五十六')
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment