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()
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')
Related
When solving a question of Project Euler I ran into the following logical error related to when n is updated.
while(n<1000):
#update n
#do something with n
#do stuff
vs
while(n<1000):
#do something with n
#do stuff
#update n
In the first instance, I ended up performing an operation with n even though the condition of n<1000 is violated.
Does this logical error have a name? How common is this bug?
I tried to look for it, I did find things about pre-incrementing and post-incrementing a variable. Although that is close to the error, it isn't exactly what is happening here. I found a reference to this in a SO answer about for loop vs while loop in the part describing how for loops are more concise and direct when compared to while loops. Essentially with while loops we end up running code after a variable update which could be buried somewhere in the code.
This is not always a bug: it depends on the algorithm. In some cases, you know that the original value of n is legal (so you can enter the loop), but you want to update and use the new value in your processing. You need to match your code to your algorithm. Your second code block is the canonical for-equivalent, and is more common.
This falls under the general heading of "off by 1 error".
I know standard CPython has a limit on recursion depth, less than 1000 I think, so the below example code will fail with a "maximum recursion depth exceeded" error.
def rec_add(x):
if x == 0:
return x
else:
return x + add(x - 1)
print(rec_add(1000))
I heard Stackless Python supports infinite recursion depth, but if I run the above code with Stackless Python, it still reports a "maximum recursion depth exceeded" error. I think maybe I need to modify the code somehow to enable it to use the infinite recursion depth feature of Stackless Python?
Any idea how to do infinite recursions in Stackless Python? Thanks.
Note: I know how to increase standard CPython's recursion depth limit over 1000, and I know how to convert the above code to a simple iteration, or simply use the Gauss formula to calculate the sum, those are not what I'm looking for, and the above code is purely as an example.
EDIT: Like I already said in the "Note" part above (that I guess no one actually reads), I know how to increase CPython's recursion limit, and I know how to convert the example code into iterations or just a Gauss sum formula of n * (n + 1) / 2, I'm just asking here because I heard one of the great features of Stackless Python is that it enables infinite recursions, and I don't know how may I enable it for the example code.
EDIT2: I'm not sure if I got the idea of "Stackless Python supports infinite recursions" wrong, but here are some sources that says (or alludes to) that Stackless Python supports infinite recursions:
What are the drawbacks of Stackless Python?
https://bitbucket.org/stackless-dev/stackless/issues/96
https://stackless.readthedocs.io/en/3.6-slp/whatsnew/stackless.html
After fumbling around I got the following code based on an official example code from more than a decade ago here
https://bitbucket.org/stackless-dev/stacklessexamples/src/a01959c240e2aeae068e56b86b4c2a84a8d854e0/examples/?at=default
so I modified the recursive addition code to look like this
import stackless
def call_wrapper(f, args, kwargs, result_ch):
result_ch.send(f(*args, **kwargs))
def call(f, *args, **kwargs):
result_ch = stackless.channel()
stackless.tasklet(call_wrapper)(f, args, kwargs, result_ch)
return result_ch.receive()
def rec_add(n):
if n <= 1:
return 1
return n + call(rec_add, n-1)
print(rec_add(1000000))
It works with large number like 1,000,000, I guess it is kind of an indirect recursion since the function calls another function which starts a tasklet that calls the function itself (or something like this).
Now I'm wondering if this is indeed the supposed way to implement an infinite recursion in Stackless Python, or are there more straight-forward/direct ways of doing it? Thanks.
I am trying to write an in-place program that would use the quicksort algorithm to sort a list. But it keeps giving an error:
maximum recursion depth exceeded while calling python object.
Although I tried setting recursion limit.
def partition(L,low,high,comparison):
i=low-1
pivot=random_pivot(L)
for j in range(low,high):
if comparison(L[j],pivot):
i+=1
L[i],L[j]=L[j],L[i]
L[i+1],L[high]=L[high],L[i+1]
return i+1
def inplace_Quicksort(L,low,high,comparison):
low=0
high=len(L)-1
if comparison(low,high):
pivot_index=partition(L,low,high,comparison)
inplace_Quicksort(L,low,pivot_index-1,comparison)
inplace_Quicksort(L,pivot_index+1,high,comparison)
print(L)
Can you please have a look at it and explain to me what is wrong? Thank you so much.
You are resetting the range to the complete list each time you call inplace_Quicksort in the first two lines of its code, thereby making the arguments low and high useless.
This leads to an endless recursion. No increase of maximum recursion depth will help you.
Instead give your arguments a default value. Look how it is done in this answer.
I saw the thread about how to keep count in a recursive function but I didn't quite follow the answer and it also didn't seem to apply to what I am looking for (at least from what I could tell so sorry if this is a repetitive question!). I am working on a piece of code to decipher text that has been Ceasar shifted in several different spots. I have constructed a recursive function that works well to shift the text until until it has found the correct shift and to return the shifted text but I am unable to get the function to return the number of times it iterated.
text_to_shift = apply_coder(text[start:], build_decoder(1))
Ltext = text_to_shift.split()
for w in Ltext:
if is_word(wordlist, w) == True:
text = ' '.join(Ltext)
return text
else:
text = ' '.join(Ltext)
return find_best_shifts_rec(wordlist, text, start)
I could write this as a while loop but I like the elegance of what I have written. I am leaning towards a global variable (which I'm going to try after this) but I feel there is a better solution. Thank you in advance for either an answer or a better explanation of the one in the thread i referred to.
def recursive_thing(calls=1):
# "calls" argument keeps track of recursion depth
if keep_recursing():
# pass a higher count to the recursive call
recursive_thing(calls + 1)
else:
print calls
return
Give your function an argument that keeps track of the recursion depth, or put the recursion in a helper function with such an argument.
In the minmax algorithm,How to determine when your function reaches the end of the tree and break the recursive calls.
I have made a max function in which I am calling the min function. In the min function , what shud I do?? For max function, I am just returning the bestscore.
def maxAgent(gameState, depth):
if (gameState.isWin()):
return gameState.getScore()
actions = gameState.getLegalActions(0);
bestScore = -99999
bestAction = Directions.STOP
for action in actions:
if (action != Directions.STOP):
score = minAgent(gameState.generateSuccessor(0, action), depth, 1)
if (score > bestScore):
bestScore = score
bestAction = action
return bestScore
def minvalue(gameState,depth,agentIndex):
if (gameState.isLose()):
return gameState.getScore()
else:
finalstage = False
number = gameState.getNumAgents()
if (agentIndex == number-1):
finalstage = True
bestScore = 9999
for action in gameState.getLegalActions(agentIndex):
if(action != Directions.STOP
I could not understand how to proceed now?I not allowed to set the limit of depth of tree. it has to be arbitrary.
Usually you want to search until a certain recursion depth (e.g. n moves in advance, when playing chess). Therefore, you should pass the current recursion depth as a parameter. You may abort earlier when your results do not improve, if you can determine that with little effort.
In the minmax algorithm,How to
determine when your function reaches
the end of the tree and break the
recursive calls.
Basically, you're asking when you've reached a leaf node.
A leaf node occurs when you've reached the maximum depth for the search, or a terminal node (i.e. a position that ends the game).
I completely agree with relet. But you might want to consider this also:
There are times when you might also think that the current branch that you are exploring is worth exploring a little deeper. This will call for some further heuristics to be applied. I don't know how advanced the solution for your problem is required to be. This is because I don't know where the problem is coming from.
As suggested by Amber, try posting some code so we know how complex you want the solution to be. Further, if you explained how much you know/can_do, then we might be able to suggest more useful options - things that you might be able to realistically implement, rather than just amazing ideas that you may not know how to or have the time to implement
This site has post of minimax, even though it is based on IronPython:
http://blogs.microsoft.co.il/blogs/dhelper/archive/2009/07/13/getting-started-with-ironpython-part-4-minimax-algorithm.aspx
It says:
The Minimax algorithm is recursive by nature, and as such it requires a stop condition, in our case either the game has ended (no more moves) or the desired depth has been reached (lines 3-8).
You can avoid having two different functions by using Negamax http://en.wikipedia.org/wiki/Negamax