gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:30:26 25 4
gpt4 key购买 nike

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

这是代码:

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

关于python - 如何在python中打印一次每个循环的所有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33506474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com