Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to write a program input a sequence positive integers and output the sequence in reverse order.

What I have tried:

I have tried this code:

def reverse(string):
    string = list(string)
    string.reverse()
    return "".join(string)
string = input()
print(reverse(string))


But the result doesn't as I expected. I want when I input "2 43 61 9", it will output "9 61 43 2", but the code output "9 16 34 2" instead.
Please help me to solve this problem.
Posted
Updated 2-Mar-23 2:03am

You might split the string, reverse the obtained list and then join the list adding blanks. That is
Python
def reverse(string):
    string = string.split()
    string.reverse()
    return " ".join(string)

string = input()
print(reverse(string))
 
Share this answer
 
You will need to break the string into separate numbers: "2", "43", "61", and "9" and then print those in reverse order. Hint: Python String split() Method[^]

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900