2

Started learning python, this is maximum sum subarray i have tried. Ending up with "maximum recursion depth exceeded in comparison". My algorithm seems ok to me. Please help me if im doing anything wrong.

import sys
import math
def maxtuple(lss,rss):
    if lss[2] > rss[2]:
        return lss
    else:
        return rss
def crosssubarray(A, start, mid, end):
    ls=rs=-sys.maxsize
    maxleft=0
    maxright=0
    sum = 0;
    for i in reversed(range(start, mid)):
        sum = sum + A[i]
        print(i)
        if sum > ls:
            ls = sum
            maxleft = i
    sum = 0
    for i in range(mid+1, end):
        sum = sum+ A[i]
        if sum > rs:
            rs = sum
            maxright = i
    return (maxleft, maxright, ls+rs)

def maxsubarray(A,start,end):
    if start == end:
        return (start,end,A[start])
    else:
        mid = (start+end)/2
        lss = maxsubarray(A, start, mid)
        rss = maxsubarray(A, mid+1, end)
        css = crosssubarray(A, start, mid, end)
        maxsub = maxtuple(lss,rss)
        maxall = maxtuple(maxsub, css)
        return maxall

A = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(maxsubarray(A,0,15))
Taku
  • 31,927
  • 11
  • 74
  • 85
Sivabushan
  • 71
  • 1
  • 8

2 Answers2

2

Your problem lies in this function:

def maxsubarray(A,start,end):
    if start == end:
        return (start,end,A[start])
    else:
        mid = (start+end)/2
        lss = maxsubarray(A, start, mid)
        rss = maxsubarray(A, mid+1, end)
        css = crosssubarray(A, start, mid, end)
        maxsub = maxtuple(lss,rss)
        maxall = maxtuple(maxsub, css)
        return maxall

To be precise, the first 5 lines. The reason for "working" (don't know your expected result) in python 2.x is because / is for floor division, while in python 3.x / is for float point division. And thanks to float point round-off error, start is mostly likely never going to be equal to end.


If integer floor division is what you're going for, you can replace the / to a //.

Doing so, the error will disappear and returns (8, 10, 32)

Taku
  • 31,927
  • 11
  • 74
  • 85
1

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Naveen Kumar M
  • 7,497
  • 7
  • 60
  • 74