最近几天在review之前同学写的图像处理代码,发现里面数字字符串中每个数字出现次数的计算过程写的有些许冗余之处。因此,我就按照自己理解的重新写了一份。
问题
计算数字字符串中每个数字字符出现的次数。
例如:
输入: 123344668
输出:
1 --> 1
2 --> 1
3 --> 2
4 --> 2
6 --> 2
8 --> 1
实现代码
本文我使用Python语言实现计算字符出现次数的过程,其他编程语言实现原理一致。
# -*- encoding:utf-8 -*-
def computePerCharNumInStr(s=None):
if s is None:
print "Please checkout the input string."
s = sorted(s)
t = s[0]
length = len(s)
keys = []
vals = []
cnt = 0
if length == 1:
cnt = 1
keys.append(t)
vals.append(cnt)
else:
for i in xrange(length):
if t == s[i]:
cnt += 1
if i == length - 1:
keys.append(s[i])
vals.append(cnt)
else:
if ((i - 1) >= 0):
keys.append(s[i - 1])
vals.append(cnt)
else:
keys.append(s[i])
vals.append(cnt)
cnt = 1
t = s[i]
if (t == s[length - 1]) and (i != length - 1):
keys.append(s[i])
cnt += 1
vals.append(cnt)
if (t == s[length - 1]) and (i == length - 1):
keys.append(s[i])
vals.append(cnt)
if len(keys) != len(vals):
print "Oops!"
else:
for i in xrange(len(keys)):
print keys[i], "-->", vals[i]
def testNumStr():
"""
Testing for computing char number for per num-char in string.
"""
computePerCharNumInStr("9")
print "Next..."
computePerCharNumInStr("123")
print "Next..."
computePerCharNumInStr("1112333445556788")
print "Next..."
computePerCharNumInStr("11123334455567889")
print "*" * 31
def testCharsStr():
"""
Testing for computing char number for per char in string.
"""
computePerCharNumInStr("t")
print "Next..."
computePerCharNumInStr("tianzhaixing")
print "Next..."
computePerCharNumInStr("ningbocity")
print "*" * 31
if __name__ == '__main__':
print "Test begin..."
testNumStr()
testCharsStr()
print "Done!"
运行结果
Test begin...
9 --> 1
Next...
1 --> 1
2 --> 1
3 --> 1
Next...
1 --> 3
2 --> 1
3 --> 3
4 --> 2
5 --> 3
6 --> 1
7 --> 1
8 --> 2
Next...
1 --> 3
2 --> 1
3 --> 3
4 --> 2
5 --> 3
6 --> 1
7 --> 1
8 --> 2
9 --> 1
*******************************
t --> 1
Next...
a --> 2
g --> 1
h --> 1
i --> 3
n --> 2
t --> 1
x --> 1
z --> 1
Next...
b --> 1
c --> 1
g --> 1
i --> 2
n --> 2
o --> 1
t --> 1
y --> 1
*******************************
Done!