64,637
社区成员
发帖
与我相关
我的任务
分享
================
Input1 Output1
2 1
A:
B:
================
Input2 Output2
4 3
A:BC
B:ACD
C:ABD
D:BC
================
Input3 Output3
4 4
A:BCD
B:ACD
C:ABD
D:ABC
#! /usr/bin/env python
def getMap(fname):
# get relationship maps
# input:
# fname: file name
# return:
# num: number of relation
# pos: a dict like A:BC
# txt: a list of lines in input file
txt = open(fname,'r').read().split('\n')
num = txt[0]
pos = dict()
for c in txt[1:]:
pos[c.split(':')[0]] = c.split(':')[1]
return (num,pos,txt)
def getNum(pos):
# get frequency number as needed
# input:
# pos: a dict with relationship maps
# return:
# the numebr needed
# can be modified to return the map
pospool = set(pos)
freqs = {}
curnum = 0
for c in pospool:
if len(freqs)==0:
curnum += 1
freqs[c] = curnum
elif pos[c]=='':
freqs[c] = curnum
else:
related_pos = pos[c]
non_connect = [x for x in freqs.keys() if x not in pos[c]]
if len(non_connect)==0:
curnum += 1
freqs[c] = curnum
else:
freqs[c] = freqs[non_connect[0]]
return max(freqs.values())
def main():
fnames = ['data1.txt','data2.txt','data3.txt']
for i in xrange(len(fnames)):
print '================'
# get relationship maps
num,pos,txt = getMap(fnames[i])
# get the frequency needed
freqs_num = getNum(pos)
# print result
print 'Input'+str(i+1)+'\tOutput'+str(i+1)
print txt[0]+'\t'+str(freqs_num)
print '\n'.join(txt[1:])
# unit test
if __name__=='__main__':
main()