user3739442
user3739442

Reputation: 1

maximum recursion depth exceeded and how to make script more efficient

I'm creating a script using this library: https://github.com/oczkers/fut14

However, after some time, I get the error "maximum recursion depth exceeded." Afterwards I did some research and saw that I could increase this, however I would like to know a better way of avoiding this error and making my script more efficient.

def search():
items = fut.searchAuctions('player', level='gold', max_buy=250, start=0, page_size=15)
print (items)
if items == 1:
    print (buy_now_price)
    print (trade_id)
    fut.bid(items[0]['trade_id'], 'buy_now_price')
elif items == 0:
    search()

Upvotes: 0

Views: 411

Answers (1)

Martin Konecny
Martin Konecny

Reputation: 59661

Most python installation only allow you to recurse 1000 levels (Python's self-imposed artificial limit).

A new "recursion level" happens every time your function search calls itself and involves saving some information of each function call on top of the stack. Once this stack has "grown" tall enough, you receive a "maximum recursion depth exceeded." also known as a stack overflow :).

You can modify your recursive algorithm to an iterative one instead to avoid this.

See this question here for an algorithmic way to convert from a recursive function to an iterative one. It involves using a list to simulate a stack (a list can grow much larger than Python's stack).

Recursive to iterative example

Although using the algorithmic way to convert a recursive to iterative function works, it's not the best approach since you are still using a growing list to represent your stack. Sometimes you can analyze your algorithm and find a way rewrite your algorithm without simulating any stack.

In your example, it seems that you simply want a function that will run forever until it finds something. You can rewrite it iteratively as follows

def search():
    while True:
        items = fut.searchAuctions('player', level='gold', max_buy=250, start=0, page_size=15
        print (items)
        if items == 1:
           break

    print (buy_now_price)
    print (trade_id)
    fut.bid(items[0]['trade_id'], 'buy_now_price')

Upvotes: 2

Related Questions