簡體   English   中英

如何在python中打印每個循環的所有結果一次

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM