-1

how to use recursion to combine the two function to one ?I know it's an answer of "move_zeros", But here I post just want to learn how to use recursion and solve problems with recursion.

func 1

def move_zeross(array):
    for i in range(len(array)):
        if array[i] is not False and array[i] == 0:
            array.pop(i)
            array.append(0)
    return array

func 2

def move_zeros(array):
    for i in range(len(array)):
        if array[i] is not False and array[i] == 0:
            move_zeross(array)
    return array

I have tried like below, but RuntimeError happens:

RuntimeError: maximum recursion depth exceeded in cmp

Here's the combined code:

def move_zeros(array):
    for i in range(len(array)):
        if array[i] is not False and array[i] == 0:
            array.pop(i)
            array.append(0)
        move_zeros(array)
    return array
Tony Wang
  • 971
  • 4
  • 16
  • 33
  • Possible duplicate of [Python Quicksort Runtime Error: Maximum Recursion Depth Exceeded in cmp](http://stackoverflow.com/questions/25105541/python-quicksort-runtime-error-maximum-recursion-depth-exceeded-in-cmp) – Peter Wood Sep 09 '16 at 07:24

2 Answers2

1

If you just want to move all zeros in the list to the end, try:

def move_zeros(array):
    result = [x for x in array if x is not 0]
    return result + [0]*(len(array)-len(result))

Using recursion:

def move_zeros(array, n=None):
    if n is None:
        n = len(array) - 1
    if n < 0:
        # no more to process
        return array
    if array[n] is 0:
        # move this zero to the end
        array.append(array.pop(n))
    return move_zeros(array, n-1)
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • yes, I know the answer. I post the question just for the learning of recursion and how to solve problem with recursion.But anyhow thanks very much for your answer – Tony Wang Sep 09 '16 at 07:46
1

A different recursive approach:

def move_zeros(array):
    if array:
        head, tail = array[0], move_zeros(array[1:])

        if head is 0:
            array = tail
            array.append(head)
        else:
            array = [head]
            array.extend(tail)

    return array

Does more list operations than acw1668's solution but is less index oriented.

cdlane
  • 40,441
  • 5
  • 32
  • 81