如何在python中打印每个循环的所有结果一次

时间:2015-11-03 18:29:13

标签: python python-2.7 loops

下面的程序要求用户输入"测试用例的数量"然后输入数字以对其进行操作。最后,我想打印循环中每个操作的结果。

这是代码:

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 

我该如何解决这个问题? 注意:我尝试将结果保存在列表中并打印出来,但它会将所有结果打印在一行中。

3 个答案:

答案 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

答案 1 :(得分:-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)

答案 2 :(得分:-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

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