0

Say you have a function

def func():
    print(1)
    print(2)
    print(3)

Does there exist some functionality in python which provides the "reverse" of this function. The reverse would print 3, print 2, and then print 1.

For longer functions (specifically, inverses in symmetric key encryption) this would be a very handy tool.

Edit: The function only consists of many independent statements as well as iteration and branching

If my function was the following

def a():
    b()
    for i in range(1,3):
        c()
        d()

Then the reverse would call: d,c,d,c,b. The interpreter would loop over the range iterator (which is [1,2]) backwards giving [2,1]. The reverse functionality would make subcalls on any iteration blocks

21
  • 3
    No. Because in a general case it won't even make any sense to reverse the code. Commented Oct 19, 2021 at 13:46
  • 1
    For functions that return a list of values, you can reverse that list. You can't unprint what was printed by the function. (Except for some serious print-redirecting decorator magic) Commented Oct 19, 2021 at 13:46
  • 2
    @tyron That makes heavy assumptions about instruction dependencies. Commented Oct 19, 2021 at 13:48
  • 1
    In particular, that there is no dependency of each instruction on the any of the previous ones. Which is of course false for virtually any non-trivial code. Commented Oct 19, 2021 at 13:51
  • 1
    foo = 3; foo += 2; if foo < 4: print("dead"); else: print("alive"). What does this code print when reversed? In what order are the statements evaluated? Commented Oct 19, 2021 at 14:22

1 Answer 1

1

The easiest way to do what you're trting to do would be to save your data to a list and then using the reverse function.

nums= ['1', '2', '3']
nums.reverse()
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks, but I'm looking for something more general
More general as in what? Be more clear so we can try to help.
@Rodrigo you have some function, f. How do you "reverse it". It isn't actually possible (at least not in Python)
I think the post is pretty clear. Given any function f, is there a set of operations you can perform on it to obtain its inverse
Oh ok, I may have been optimistic
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.