2015-11-03 709 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 

我认为这是非常接近你想要的。

相关问题