Python object exceeds recursion depth - python-3.x

I'm writing this program to process some lab results for college written in a .txt file. However, when I launch the program,it says there's a recursion error and the python object exceeds recursion depth. How can I solve this?
from math import *
from numpy import *
D=0.946
iD=0.001
diametros=loadtxt("bolas.txt",delimiter=",")
ind=loadtxt("incertezas.txt",delimiter=",")
for d in diametros :
for incertd in ind:
a=1+(9*d/(4*D))+(9*d/(4*D))**2
def incerteza(D,d,incertd,iD):
incert= sqrt((((9/(4*D))+(9*d/(2*D**2))*incertd)**2+(((-9*d/(4*D**2))+(-9*d/(2*D**3)))*iD)**2))
return incerteza(D,d,incertd,iD);
j=incerteza(D,d,incertd,iD)
r.append(a)
i.append(j)
print (r,i)

The culprit is in here:
def incerteza(D,d,incertd,iD):
incert= sqrt((((9/(4*D))+(9*d/(2*D**2))*incertd)**2+(((-9*d/(4*D**2))+(-9*d/(2*D**3)))*iD)**2))
return incerteza(D,d,incertd,iD);
The function incerteza keeps calling itself, with the exact same parameters, over and over and over again.
Maybe you meant to return incert ?

Related

unpaking with * operator in Numba

Im trying to run a code like this,
from numba import njit
#njit
def fun(x):
one,*two = x
print(two)
fun([1,2,3])
But, when I tried to run , it give me the following error mesage:
UnsupportedError: Use of unsupported opcode (UNPACK_EX) found
I need that code structure because I´m using scipy.optimize.minimize that admits only 1 argument, and the lenght of x varies depending on the model

Python: signature with Numba

I have a function that is doing some computation and at a certain point is calling another one. For example, the main function is something like:
import numba
#numba.njit(some signature here)
def my_funct():
...
value = cosd(angle)
Since the function cosd is inside another function decorated with numba.njit, it has to be decorated as well, and in my case it is:
from numba import float64
#numba.njit(float64(float64))
def cosd(angle):
return np.cos(np.radians(angle))
My problem now is that in another function, the input value angle is an array and the related output is an array as well. I know that I could decorate my function as #numba.njit(float64[:](float64[:])) but doing so the function would not accept scalars anymore. How can I can tell numba that input is something like Union[float64, float64[:]]? Of course this applies to the output as well. Thanks a lot!
I finally found an answer myself.
The solution is to create a list of signatures so, for my example, it would be:
from numba import float64
#njit([float64(float64), float64[:](float64[:])])
def cosd(angle):
return np.cos(np.radians(angle))
I hope this will be helpful to others.

How to replace the call to random.randint() in a function tested with pytest?

I'm new to programming and did search a lot through the questions but couldn't find an answer to my present problem.
I am writing a little game in python 3.8 and use pytest to run some basic tests.
One of my tests is about a function using random.randint()
Here's an extract of my code :
import random
...
def hit(self, enemy, attack):
dmg = random.randint(self.weapon.damage_min, self.weapon.damage_max) + self.strength // 4
hit() does other things after that but the problem is with this first line.
I tried to use monkeypatching to get a fake random number for the test :
def test_player_hit_missed(monkeypatch, monster, hero):
monkeypatch.setattr('random.randint', -3)
hero.hit(monster, 'Scream')
assert monster.life == 55
When I run the test, I get this error :
TypeError: 'int' object is not callable
From what I understand, the monkey-patch did replace randint() by the number I indicated (-3), but then my function hit() did try to call it nonetheless.
I thought -3 would replace randint()'s result.
Can someone explain me :
- why this doesn't work (I probably haven't correctly understood the behavior of the monkeypatch) ?
- and how I can replace the call to random.randint() by the value -3 during the test ?
Thanks

Can't understand why "frozen" random variable isn't working right from scipy.stats in Python

I've used frozen Random Variables (RVs) from scipy.stats in Python. For reasons I can't understand I get different behavior between a script and an interactive session:
from scipy.stats import norm, lognormal
import math as math
RV = lognorm(s=.8325546, scale=math.exp(-.34657359)) # frozen RV with many attributes
print("\ntrial of lognorm: ")
print(" " + str(lnRV(2)))
fails, saying:
TypeError: 'rv_frozen' object is not callable
Oddly, I can get this to work OK in an interactive session, for both the normal and lognormal:
Any idea what's going on here?
Stupid on my part...I am defining an instance using RV, but then trying to call an instance using lnRV.

How to get cProfile results from a callback function in Python

I am trying to determine which parts of my python code are running the slowest, so that I have a better understanding on what I need to fix. I recently discovered cProfile and gprof2dot which have been extremely helpful. My problem is that I'm not seeing any information about functions that I'm using as callbacks, which I believe might be running very slowly. From what I understand from this answer is that cProfile only works by default in the main thread, and I'm guessing that callbacks use a separate thread. That answer showed a way to get things working if you are using the threading library, but I couldn't get it to work for my case.
Here is roughly what my code looks like:
import rospy
import cv
import cProfile
from numpy import *
from collections import deque
class Bla():
def __init__( self ):
self.image_data = deque()
self.do_some_stuff()
def vis_callback( self, data ):
cv_im = self.bridge.imgmsg_to_cv( data, "mono8" )
im = asarray( cv_im )
self.play_with_data( im )
self.image_data.append( im )
def run( self ):
rospy.init_node( 'bla', anonymous=True )
sub_vis = rospy.Subscriber('navbot/camera/image',Image,self.vis_callback)
while not rospy.is_shutdown():
if len( self.image_data ) > 0:
im = self.image_data.popleft()
self.do_some_things( im )
def main():
bla = Bla()
bla.run()
if __name__ == "__main__":
cProfile.run( 'main()', 'pstats.out' ) # this could go here, or just run python with -m cProfile
#main()
Any ideas on how to get cProfile info on the vis_callback function? Either by modifying the script itself, or even better using python -m cProfile or some other command line method?
I'm guessing it is either the reading of images or appending them to the queue which slow. My gut feeling is that storing them on a queue is a horrible thing to do, but I need to display them with matplotlib, which refuses to work if it isn't in the main thread, so I want to see exactly how bad the damage is with this workaround

Resources