-3

I am writing a python function that prints the reverse of a given function. My solution should be for example if the given expression is 200+500-600 my output should be 600-500+200. My code however is giving me 006-005+200. Any help on how to fix, here's my code.

    def reverse(s): 
    if len(s) == 0: 
        return s 
    else: 
        return reverse(s[1:]) + s[0] 

s = "100+200-300"

print ("The original string is : ",end="") 
print (s) 

print ("The reversed string(using recursion) is : ",end="") 
print (reverse(s))
Jennifer
  • 11
  • 2
  • 4
    The obvious problem is that you've reversed the string, character by character, instead of doing what you say you want: reverse the order of the expression elements. You have to separate the numbers as whole tokens. The term you may be missing is "parsing"; try a search for "expression parsing" and work from there. – Prune Oct 17 '18 at 17:22
  • In what sense is `600-500+200` the "reverse" of `200+500-600`? You need to use a parser to parse arithmetic expressions. – Håken Lid Oct 17 '18 at 17:30
  • 1
    You might be interested in SymPy. Though it could be an overkill for this case. – Georgy Oct 17 '18 at 17:35
  • @Georgy This is such a simple problem there is no need for a external library for it – Agile_Eagle Oct 17 '18 at 17:38
  • Do you want algebraic consistency? 200+500-600 != 600-500+200. – Makoto Oct 17 '18 at 17:55
  • no, just to print in reverse order as given – Jennifer Oct 17 '18 at 18:13
  • Your `print` statement makes it look like you have to use recursion. In this case, I would suggest splitting the string to create a list and then recursively reverse the list. This is pretty simple if there are spaces in the equation string. Without spaces though, you'll likely have to use some sort of a [reg-ex](https://stackoverflow.com/a/1059601) to create the list. – Mr. Kelsey Oct 17 '18 at 19:09

1 Answers1

0

Use .split() to break up your string and then .join() the reversed list

s = '200 + 500 - 600'
lst = s.split()
print(' '.join(lst[::-1]))
# 600 - 500 + 200
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20