Home > Back-end >  Getting None while reversing list in python
Getting None while reversing list in python

Time:12-24

The code is quite easy but its returning 'None', i do not know why. Can someone please correct my code.

Edit : New to programming, this is question at the end of chapter of recursion. Please don't downvote.

def rev(x):
    global y
    if len(x)==0:
        return y

    else:
        y=y [x[-1]]
        x.pop(-1) #Remove last item from list
        rev(x)

z=[1,2,3]
y=[]
print(rev(z))

CodePudding user response:

Thank you but I'm supposed to use recursion...

Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like mutation, variable reassignments, and other side effects.

  1. if the input t is empty, return the empty result
  2. (inductive) t has at least one element. prepend the result of the sub-problem rev(t[1:0) to a singleton list of the first element, [t[0]]
def rev(t):
  if not t:
    return []            # 1. empty t
  else:
    rev(t[1:])   [t[0]]  # 2. at least one element

A function without side effects will always return the same result for the same input. This allows us to substitute and function call for its output and easily visualize its computational process -

rev([1,2,3,4,5])
== rev([2,3,4,5])   [1]
== rev([3,4,5])   [2]   [1]
== rev([4,5])   [3]   [2]   [1]
== rev([5])   [4]   [3]   [2]   [1]
== rev([]) [5]   [4]   [3]   [2]   [1]
== []   [5]   [4]   [3]   [2]   [1]
== [5]   [4]   [3]   [2]   [1]
== [5,4]   [3]   [2]   [1]
== [5,4,3]   [2]   [1]
== [5,4,3,2]   [1]
== [5,4,3,2,1]

CodePudding user response:

Here's an example of how you could reverse the contents of a list in situ without slicing or recursion (not that you'd ever want to do it this way):

def rev(x):
    i = 0
    j = len(x)
    while (j := j - 1) > i:
        x[i], x[j] = x[j], x[i]
        i  = 1
    return x

print(rev([1,2,3,4,5]))
  • Related