2012-09-12 36 views
0

我試圖打印出每個單獨行中最大路徑的輸出。在python中打印出單獨的行輸出

的代碼是在這裏:

def triangle(rows): 
    PrintingList = list() 
    for rownum in range (rows):  
     PrintingList.append([]) 
     newValues = map(int, raw_input().strip().split()) 
     PrintingList[rownum] += newValues 
    return PrintingList 

def routes(rows,current_row=0,start=0): 
     for i,num in enumerate(rows[current_row]): 
      if abs(i-start) > 1: 
       continue 
      if current_row == len(rows) - 1: 
       yield [num] 
      else: 
       for child in routes(rows,current_row+1,i): 
        yield [num] + child 

testcases = int(raw_input()) 
output = [] 
for num in range(testcases): 
    rows= int(raw_input()) 
    triangleinput = triangle(rows) 
    max_route = max(routes(triangleinput),key=sum) 
    output.append(sum(max_route)) 

print '\n'.join(output) 

我嘗試這樣做:

2 
3 
1 
2 3 
4 5 6 
3 
1 
2 3 
4 5 6 

當我嘗試輸出出來的值,我得到這個:

print '\n'.join(output) 
TypeError: sequence item 0: expected string, int found 

如何變化這個?需要一些指導...

回答

4

試試這個:

print '\n'.join(map(str, output)) 

Python中只能加入串在一起,所以你應該首先將整數轉換爲字符串。這就是map(str, ...)部件所做的。

+0

任何其它的辦法只有打印爲INT ...... – lakesh

+1

輸出有打印整數,沒有什麼區別將其轉換爲字符串然後打印它(就像我的例子)。當你打印一個整數時,它會在幕後轉換爲一個字符串。 – grc

2

@grc是正確的,但的,而不是創建包含換行符一個新的字符串,你可以簡單地做:

for row in output: 
    print row