[英]How to print all the result of each loop one time in 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
我该如何解决这个问题?
注意:我尝试将结果保存在列表中并打印,但它会将所有结果打印在一行中。
#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
你的缩进有一些问题,但我假设这只是在问题中,而不是在真正的程序中。
因此,您希望首先输入所有测试用例,执行它们,最后显示结果。 要获得测试用例,您可以执行类似的操作
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)
如果要在同一行上打印序列,可以执行以下操作。
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
我认为这非常接近你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.