2015-11-03 88 views
3

下面的程序要求用戶輸入「測試用例的數量」,然後輸入數字以對其進行操作。最後,我想打印循環中每個操作的結果。如何在python中一次打印每個循環的所有結果

這是代碼:

test_case = int(raw_input()) # User enter here the number of test case 
for x in range(test_case): 
    n = int(raw_input()) 

while n ! = 1: # this is the operation 
    print n,1, # 
    if n % 2 == 0:  
     n = n//2 
    else:     
     n = n*3+1 

下面是輸出,如果我在測試情況下輸入「2」,並在每種情況下2號。對於實施例22和64將是這樣的:

2 
22 # the first number of the test case 
22 1 11 1 34 1 17 1 52 1 26 1 13 1 40 1 20 1 10 1 5 1 16 1 8 1 4 1 2 1 # it prints the result immediately 
64 # second test case 
64 1 32 1 16 1 8 1 4 1 2 1 # it prints it immediately as the first 

下面是所期望的輸出:

2 
22 
64 

用戶後輸出進入測試案例和測試用例的所有數目是:

22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 
64 32 16 8 4 2 1 

我該如何解決這個問題?
注:我試圖將結果保存在列表中並打印出來,但它將所有結果打印在一行中。

+1

'對於結果的結果:打印result' –

+0

請你能把它放在我的代碼,並添加它,請我不知道在哪裏我就會把它和感謝你 –

回答

1
#Gets the number of test cases from the user 
num_ops = int(raw_input("Enter number of test cases: ")) 

#Initilze the list that the test cases will be stored in 
test_cases = list() 

#Append the test cases to the test_cases list 
for x in range(num_ops): 
    test_cases.append(int(raw_input("Enter test case"))) 

#Preform the operation on each of the test cases 
for n in test_cases: 
    results = [str(n)] 
    while n != 1: # this is the operation 
     if n % 2 == 0:  
      n = n//2 
     else:     
      n = n*3+1 
     results.append(str(n)) 
    print ' '.join(results) 

完全按照您所描述的那樣輸出,但輸入文本提示爲了增加清晰度。

enter number of test cases: 2 
enter test case: 22 
enter test case: 64 
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 
64 32 16 8 4 2 1 
+0

夢幻般的許多感謝你 –

-2

你的縮進有一些問題,但我假設只是在問題中,而不是在真正的程序中。

所以你想先輸入所有的測試用例,執行它們,最後顯示結果。 要獲得測試情況下,你可以這樣做

num_test_cases = int(input()) 
test_cases = [0] * num_test_cases 
for x in range(num_test_cases): 
    test_cases.append(input()) 

之後,你可以執行你與你有相同的編碼算法,但在列表中保存結果(如你所提到的)

... 
results = {} 
for x in test_cases: 
    n = int(x) 
    results[x] = [] 
    while n != 1: 
     results[x].append(n) 
     ... 

你終於可以打印出您的結果

for result in results 
    print(results) 
+0

你的第一個代碼塊犯規反映出他想要怎樣的輸入測試用例(多次請求輸入),你應該顯示你是如何初始化'results' /你沒有初始化'results',這意味着調用'results [x]'會導致錯誤 –

+0

好的,修復那些問題。 – fcortes

+0

不,我可以修復它,請你可以再次上傳我的代碼,並把它編輯爲 –

-2

如果你要打印在同一行的順序,你可以做到以下幾點。

test_case=int(raw_input()) # User enter here the number of test case 
for x in range(test_case): 
    n=int(raw_input()) 
    results = [] 
    while n != 1: # this is the operation 
     results.append(n) 
     if n % 2 == 0:  
      n=n//2 
     else:     
      n=n*3+1 
    print(' '.join(results)) # concatenates the whole sequence and puts a space between each number 

我認爲這是非常接近你想要的。

相關問題