百练 1002题


题目参见:http://bailian.openjudge.cn/practice/1002/


python代码:

解法1,内存占用大。

getinf() 从本地文本文件中读取输入数据,返回输入字符串列表。

getins()从标准输入读取数据,返回输入字符串列表。

strimch()删除字符串中的指定字符,返回一个新字符串。

char2d()把一个大写字母组成的字符串转换成数字字符串,返回新字符串。

formatu()在指定数字字符串中第三个字符后增加“-”符号,返回一个新字符串。

repcount() 计算数字字符串列表中每个列表成员的重复次数,输出统计结果。


# qpyhton3 & android
# 2017.03.15 lengyanju
# beilian Question No.1002

def getinf():
	FILE = "/sdcard/documents/t1003.txt"
	f = open(FILE)
	inlist = []
	f.readline()
	for line in f:
		inlist.append(line.strip('\n'))
	return inlist
	
def getink():
	line1 = input() 
	rel = [0 for x in range(int(line1))]
	for x in range(int(line1)):
		rel[x] = input()
	return rel
	
def char2d(s):
	d = ''
	rel = ''
	for a in s:
		if a >= 'A' and a <= 'Z':
			if a=='A' or a == 'B' or a =='C':
				d=2
			elif a=='D' or a == 'E' or a =='F':
				d=3
			elif a=='G' or a == 'H' or a =='I':
				d=4
			elif a=='J' or a == 'K' or a =='L':
				d=5
			elif a=='M' or a == 'N' or a =='O':
				d=6
			elif a=='P' or a == 'R' or a =='S':
				d=7
			elif a=='T' or a == 'U' or a =='V':
				d=8
			elif a=='W' or a == 'X' or a =='Y':
				d=9
			rel += str(d)
		else:
		 rel += a
	return rel

def strimch(s, ch)	:
	b = ''
	if ch in s:
		for c in s:
			if c!= ch and c is not '\n':
					b += c
		return b
	else:
		return s
	
def delx(dlist):
	d1 = []
	for line in dlist:
		# add pure digital into list
		d1.append(char2d(strimxx(line,'-')))
	return d1
	
def formatu(i)	:
	s = str(i)
	return s[0:3]+'-'+s[3:]
	
def repcount(d):
	val = [0 for i in range(9999999)]
	n = []
	for a in d:
		if int(a) not in n:
			n.append(int(a))
		val[int(a)] += 1
		
	# After sort, then output.
	n.sort()
	for v in n:
		if val[v] > 1:
			print("%s %d"%(formatu(v),val[v]))

def main():
	inlist = getinf()
	outlist = delx(inlist)
	repcount(outlist)

if __name__=='__main__':
	main()



2. 速度快。需要改变获取输入的地方。

def char2d(s):
	d = ''
	rel = ''
	for a in s:
		if a >= 'A' and a <= 'Z':
			if a=='A' or a == 'B' or a =='C':
				d=2
			elif a=='D' or a == 'E' or a =='F':
				d=3
			elif a=='G' or a == 'H' or a =='I':
				d=4
			elif a=='J' or a == 'K' or a =='L':
				d=5
			elif a=='M' or a == 'N' or a =='O':
				d=6
			elif a=='P' or a == 'R' or a =='S':
				d=7
			elif a=='T' or a == 'U' or a =='V':
				d=8
			elif a=='W' or a == 'X' or a =='Y':
				d=9
			rel += str(d)
		else:
		  rel += a
	d = rel[0:3]+'-'+rel[3:]
	return d
	

FILE="./t1002.txt"
f = open(FILE)
b = ''
i = 0
dlist = []
kv = dict()

for line in f:
	if '-' in line:
		for ch in line:
			if ch != '-'and ch is not '\n':
				b += ch
	else:
		b = line
			
	b = b.strip('\n')
	
	# char to digitl
	d = char2d(b)
	
	# append to digitl list
	dlist.append(d)
	
	# initilize next stepb
	b=''
	i += 1

f.close()

for d in dlist:
	if dlist.count(d) > 1:
		if d not in kv.keys():
			kv[d] = dlist.count(d)

for k in sorted(kv.keys()):
	print("%s %d"%(k,kv[k]))

运行结果:

百练 1002题_第1张图片



你可能感兴趣的:(Python,python,android,win7)