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)
Related
I would like to find an approximate value for the number pi = 3.14.. by using the Newton method. In order to use it also for some other purpose and thus other function than sin(x), the aim is to implement a generic function that will be passed over as an argument. I have an issue in passing a function as an argument into an other function. I also tried lambda in different variations. The code I am showing below produces the error message: IndexError: list index out of range. I will appreciate your help in solving this issue and eventually make any suggestion in the code which may not be correct. Thanks.
from sympy import *
import numpy as np
import math
x = Symbol('x')
# find the derivative of f
def deriv(f,x):
h = 1e-5
return (lambda x: (f(x+h)-f(x))/h)
def newton(x0,f,err):
A = [x0]
n = 1
while abs(A[n]-A[n-1])<=err:
if n == 1:
y = lambda x0: (math.f(x0))
b = x0-y(x0)/(deriv(y,x0))
A.append(b)
n += 1
else:
k = len(A)
xk = A[k]
y = lambda xk: (math.f(xk))
b = newton(A[k],y,err)-y(newton(A[k],y,err))/deriv(y,k)
A.append(b)
n += 1
return A, A[-1]
print(newton(3,math.sin(3),0.000001))
I don't know why you use sympy because I made it without Symbol
At the beginning you have to calculate second value and append it to list A and later you can calculate abs(A[n]-A[n-1]) (or the same without n: abs(A[-1] - A[-2])) because it needs two values from this list.
Other problem is that it has to check > instead of <=.
If you want to send function sin(x) then you have to use math.sin without () and arguments.
If you want to send function sin(3*x) then you would have to use lambda x: math.sin(3*x)
import math
def deriv(f, x, h=1e-5):
return (f(x+h) - f(x)) / h
def newton(x0, f, err):
A = [x0]
x = A[-1] # get last value
b = x - (f(x) / deriv(f, x)) # calculate new value
A.append(b) # add to list
while abs(A[-1] - A[-2]) > err: # it has to be `>` instead of `<=`
x = A[-1] # get last value
b = x - (f(x) / deriv(f, x)) # calculate new value
A.append(b) # add to list
return A, A[-1]
# sin(x)
print(newton(3, math.sin, 0.000001)) # it needs function's name without `()`
# sin(3*x)
print(newton(3, lambda x:math.sin(3*x), 0.000001))
# sin(3*x) # the same without `lambda`
def function(x):
return math.sin(3*x)
print(newton(3, function, 0.000001))
Result:
([3, 3.1425464414785056, 3.1415926532960112, 3.141592653589793], 3.141592653589793)
([3, 3.150770863559604, 3.1415903295877707, 3.1415926535897936, 3.141592653589793], 3.141592653589793)
EDIT:
You may write loop in newton in different way and it will need <=
def newton(x0, f, err):
A = [x0]
while True:
x = A[-1] # get last value
b = x - (f(x) / deriv(f, x)) # calculate new value
A.append(b) # add to list
if abs(A[-1] - A[-2]) <= err:
break
return A, A[-1]
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
Description:
I have three variable a, x and y. I want to apply the following, if variable a in range(x, y) print the a variable
Code:
a = "0.50"
x = "-14.40"
y = "0.50"
for a in range(int(x), int(y)):
print a
Error (of course):
ValueError: invalid literal for int() with base 10: '-14.40'
Pythonista i need your help here please!!
The Python 2 range function is irrelevant for this task. You just need to convert those strings to floats and do simple comparison tests. Eg,
a = "0.50"
x = "-14.40"
y = "0.50"
afloat = float(a)
if float(x) <= afloat and afloat <= float(y):
print a
output
0.50
This can be written more simply (and more efficiently) using Python's comparison chaining.
a = "0.50"
x = "-14.40"
y = "0.50"
if float(x) <= float(a) <= float(y):
print a
FWIW, in Python 3, the range object can be useful for testing membership of a range, but it wouldn't be useful for your case. Eg,
>>> r = range(1, 10, 2)
>>> list(r)
[1, 3, 5, 7, 9]
>>> 3 in r
True
>>> 4 in r
False
>>> 3.5 in r
False
From the comments
i need to check if a in range of x and y or not.
Then do
a = "0.50"
x = "-14.40"
y = "0.50"
if float(x) <= float(a) <= float(y): # checks a is between x and y (inclusive)
# do something
range does something very different. It is for making iterators which we can use in for loops, like this:
for i in range(4):
print(i * 2)
0
2
4
6
You can use numpy arange.
import numpy as np
r = np.arange(-14.4,0.5, 0.5)
def isinside(x):
if x in r:
print ("x")
else:
print ("x no in a")
isinside(-12)
returns
x no in a
If you want to print the whole serie
print ([round(x) for x in r])# round to avoid long numbers
Some more information https://pynative.com/python-range-for-float-numbers/
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))
a = 100
x = 1000
def myFun(a,b):
x = b-a
return x
a = myFun(a,x)
x = myFun(a,x)
print(x+a)
I know in first function, a = myFun(a,x) is 900, but why is the result of x = myFun(a,x) ,100?
The name x inside the function myFunc() is independent from the global name x. They live in different namespaces.
As such, when you call myFunc(a, x) the first time, the global x value is unchanged; it remains 1000:
>>> a = 100
>>> x = 1000
>>> def myFun(a,b):
... x = b-a
... return x
...
>>> myFun(a,x)
900
>>> x
1000
If you wanted the global x to change when calling myFunc(), you need to tell Python explicitly that x is to be treated as a global in the function:
def myFun(a,b):
global x
x = b-a
return x
Now assigning to x in the function will set the global name x:
>>> a = 100
>>> x = 1000
>>> def myFun(a,b):
... global x
... x = b-a
... return x
...
>>> myFun(a,x)
900
>>> x
900