Not recognized variable inside a loop in Python - python

I am trying to run loop in Python while specifying the variable x and y inside the loop. When I run the following loop:
my_funcs = {}
for i in range(len(data) - 1):
def foo(x, y):
x = data[i]['body']
y = data[i+1]['body']
tfidf = vectorizer.fit_transform([x, y])
return ((tfidf * tfidf.T).A)[0,1]
foo.func_name = "cosine_sim%d" % i
my_funcs["cosine_sim%d" % i] = foo
print(foo(x,y))
I get the strange error: x is not defined in the line print(foo(x,y)) Any idea why on earth this might be happening since I have stated that x = data[i]['body'] ?
Thanks in advance

If everything else is correct, I think you should move that method outside of the loop.
You only defined x within foo, so the print line doesn't know about it. Plus, you were overwriting the x parameter of foo anyways
def foo(x, y):
tfidf = vectorizer.fit_transform([x, y])
return ((tfidf * tfidf.T).A)[0,1]
my_funcs = {}
for i in range(len(data) - 1):
x = data[i]['body']
y = data[i+1]['body']
foo.func_name = "cosine_sim%d" % i
my_funcs["cosine_sim%d" % i] = foo
print(foo(x,y))

Related

get a specific value from a function when function is given to as an argument?

I have a function that needs to give a specific value to an other function depending on the current iteration in a for loop. the get_change_vector returns a tuple of 4 elements depending on the iteration a want to get a specific value from it.
def get_change_vector(x, r,):
Xp = r*x + x**3 - x**5
Xp2 = r*x + x**2 - x**3
Xp3 = r*x -x/(1+x**2)
Xp4 = x-r+(2-x)/(1+x**2)
return (Xp, Xp2, Xp3, Xp4)
def main ():
for n in range (4):
Xs = [i for i in np.arange(-2, 2, 0.001)]
rs = [funcR(x)[n] for x in Xs]
i1, i2 = 0 if n < 2 else 1, 0 if n % 2 ==0 else 1
ax = axes[i1] [i2]
for x, r in zip (Xs, rs):
clr = 'g' if is_stable(get_change_vector,x, r) else 'r'
ax.plot(r, x, 'o', color=clr, markersize=0.1)
I tried to give a specific index to get_change_vector but it returns an error saying function is not subcriptable.
I tried making a variable of the needed function
function = get_change_vector(x,r)[n]
but this returned an error this is because of the what the is_stable when it reaches func(*args)
'numpy.float64' object is not callable
def get_derivative(func, n, i):
'''
Wrapper around our change_vector function
so derivative can handle multiple parameters
'''
def wraps(n):
args = i, n
return func(*args)
return derivative(wraps, n, dx=1e-6)
def is_stable(func, n , i ):
return get_derivative(func, n, i) < 0

Loop a function using the previous output as input

When my function foo generating a new element, I want to reuse the output and put it in foo n-times. How can I do it?
My function:
def foo(x):
return x + 3
print(foo(1))
>>>4
For now. I'm using this method:
print(foo(foo(foo(1))))
There are a couple ways to do what you want. First is recursion, but this involves changing foo() a bit, like so:
def foo(x, depth):
if depth <= 0:
return x
return foo(x+3, depth-1)
and you'd call it like foo(1, n)
The other way is with a loop and temp variable, like so
val = 1
for _ in range(0, n):
val = foo(val)
Use a loop for this:
value = 1
for i in range(10):
value = foo(value)
def foo(x,y):
for i in range(y):
x = x + 3
return x
print (foo(10,3))
Output:
19
What you are searching for is called recursion:
def foo(x, n=1):
if n == 0:
return x
return foo(x + 3, n - 1)
Another possible with lambda and reduce
Reduce function
from functools import reduce
def foo(x):
return x + 3
print(reduce(lambda y, _: foo(y), range(3), 1))
You will get 10 as result
# y = assigned return value of foo.
# _ = is the list of numbers from range(3) for reduce to work
# 3 = n times
# 1 = param for x in foo

Python - Convert prefixes (kilo etc) to base number

I have numbers which end in k meaning e^3. I have written a function to try and solve this problem:
def prefixFinder(in1, out1):
if in1.endswith('k'):
in1 = in1[:-1] # Remove k from the end
out1 = float(in1) * 1000 # Multiply by 100
print(out1)
return out1 # Return out1
When I call the function with x ( Want to replace the current value of x, '10k' with 10000.0
x = '10k'
prefixFinder(x, x)
print(x)
The output I get is '10k'. But the print(out1) in the function is 10000.0 which is correct.
Im not sure what I have done wrong and anyhelp is greatly appreaciated
Out arguments like those in C or C# don't exist in Python, you have to return it:
def prefixFinder(i):
if in1.endswith('k'):
i = i[:-1] # Remove k from the end
return float(i) * 1000 # Multiply by 100
And then use it like so:
x = '10k'
x = prefixFinder(x)
print(x)
You only need to give an input (x='10k') to make the function and after you need to return the result.
def prefixFinder(x):
if x.endswith('k'):
x = x[:-1]
return float(x) * 1000
y = '10k'
y = prefixFinder(y)
print(y)
In this case the result will be:
10000.0
You can also assign the return to a variable:
def prefixFinder(x):
if x.endswith('k'):
x = x[:-1]
out = float(x) * 1000
return out
y = '10k'
y = prefixFinder(y)
print(y)
You don't need to pass out1 param to your function. Just do:
def prefixFinder(in1):
if in1.endswith('k'):
in1 = in1[:-1] # Remove k from the end
out = float(in1) * 1000 # Multiply by 100
print(out)
return out
x = "10k"
x = prefixFinder(x)
print(x)

Why does my lambdify not working when add my own function

I created a function and make it usable in my Sympy expression like this:
def Unit(x):
if(x != 0):
return 0
else:
return 1
Unit = Function('Unit')
x = Symbol('x')
My expression:
fx = x ** 2 + Unit(x)
But when I run:
lam_f = lambdify(x, fx, modules=["sympy"])
print(lam_f(-1))
It said that my Unit is not defined?
Can anyone explain where i went wrong?
Function('Unit') returns an undefined function with name Unit. See this question. If you want to use your previously defined function Unit, remove the call to Function():
def Unit(x):
if(x != 0):
return 0
else:
return 1
x = Symbol('x')
fx = x**2 + Unit(x)
lam_f = lambdify(x, fx, modules=['sympy'])
print(lam_f(-1)) # prints 1

Pass references to a python function

In this example (which does not work)
def foo(x,y):
x = 42
y = y * 2
x = 0
y = 2
foo(x,y)
I would like x = 42 and y = 4.
The idea behind is to have a wrapper to C functions using ctypes:
def foo(self, x, y):
error = self.dll.foo(self.handler, x, pointer(y))
if error:
self.exception(error)
How can I pass parameters as references in Python?
Like #musically_ut, you cannot pass primitive values by reference, but you can get newest values by returning from function. Like this:
def foo(x,y):
x = 42
y = y * 2
return x,y
x = 0
y = 2
x,y=foo(x,y)

Categories

Resources