Home > Software engineering >  Python reversible functions
Python reversible functions

Time:10-20

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

CodePudding user response:

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()

CodePudding user response:

You can do this with recursive function like below:

def func(n):
    if n>3:return
    func(n 1)
    print(n)
    return

func(1)

Output:

3
2
1
  • Related