1
我想實現一類叫做矩陣內海峽方法 我當前的代碼是__str__方法返回集合的垂直的Python
類矩陣(對象):
def __init__(self): # no modification is needed for this method, but you may modify it if you wish to
'''Create and initialize your class attributes.'''
self._matrix = []
self._rooms = 0
def read_file(self,fp): #fp is a file pointer
'''Build an adjacency matrix that you read from a file fp.'''
rooms = fp.readline()
rooms = int(rooms)
self._matrix= [set() for _ in range(rooms+1)]
for line in fp:
line=line.strip()
item=line.split()
item2=int(item[0])
item3=int(item[1])
self._matrix[item2].add(item3)
self._matrix[item3].add(item2)
return self._matrix
def __str__(self):
'''Return the matrix as a string.'''
s=''
matrix=self._matrix
for n in range(len(matrix)-1):
s=s+"{}:{} ".format(n+1,matrix[n+1])
return s
當前時我打印str()方法得到輸出: 1:{2} 2:{1,3} 3:{2,4} 4:{3,5} 5:{4,6 } 6:{5}
我想印的是:
1:2
2:1 3
3:2 4
4:3 5
5:4 6
6:5
任何建議?
*咳嗽*'」」。加入(...)' –
你不需要串對於這一點,只是做像''」在矩陣X「」。加入(STR(X) [n + 1])' – acushner
即時獲取模塊'字符串'沒有屬性'加入'錯誤? –