Home > Mobile >  How to convert the output into a single line
How to convert the output into a single line

Time:09-30

#python
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))

rev=arr[::-1]
for i in range(n):
    final=0
    final =rev[i]
    print(final)

Given an array of integers, print the elements in reverse order as a single line of space-separated numbers.

CodePudding user response:

You are calling input() many times which is not required, also you can use the join function with " " separator to print all the elements of array in one line. Please note that join expects all elements as str so you will have to map it back to str, so it's better to avoid the map to int at the initial stage as we will have to map it back to str
Here is one of the approach:

n = input("Enter the sequence of numbers: ").strip()
arr = n.split()
print (" ".join(arr[::-1]))

Output:

Enter the sequence of numbers: 1 3 5 7 9
9 7 5 3 1

CodePudding user response:

u may use join method for concat string sequences

but in your case u need to transform integers to string type

in the end code will be like this: reversed_string = ' '.join(map(str, rev))

  • Related