I'm trying to convert the following Pinescript function into Python.
xrf(values, length) =>
r_val = float(na)
if length >= 1
for i = 0 to length by 1
if na(r_val) or not na(values[i])
r_val := values[i]
r_val
r_val
The attempt that I've made so far to convert to Python is as follows...
import math
#Function 1
def xrf(values, length):
r_val = float("NaN")
if length >= 1:
for i in range(0, length):
if math.isnan(r_val) or not math.isnan(values[I]):
r_val = values[i]
The code works fine up until the bit that reads math.isnan(values[i]). In particular, the problematic bit seems to be the square brackets and the i.
Therefore, I was wondering if anyone knew what the 'series subscript' is for Python - this is the operator that I'm struggling to convert.
Here's an example of the function in a small snippet of code, with the error message that it returns.
import examplemodule
from examplemodule import xrf
variable = xrf(6,50)
print(variable)
The error message that this returns is...
Traceback (most recent call last):
File "mypath/script.py", line 4, in <module>
variable = xrf(6,50)
File "mypath/examplemodule.py", line 9, in xrf
r_val = values[i]
TypeError: 'int' object is not subscriptable
Related
As the Topic says, module is not callable and I don't really understand why. Its (probably) not the same problem from the similar post, at least I don't know what should I import. I am using SymPy.
And this is a full error text:
Traceback (most recent call last):
File "C:\Users\Marek\Desktop\Bartłomiej\SymPy\PrimeTest.py", line 16, in <module>
if isinstance(evalf((n/p).subs(x, 1)), int):
TypeError: 'module' object is not callable
Full code:
from sympy import *
import math
import sys
import mpmath
sys.modules['sympy.mpmath'] = mpmath
x, y = symbols(' x y ')
#p = sympfy(input(Check this: ))
p = 100
n = expand(((x-1)**p - (x**p - 1)))
print(n)
if isinstance(evalf((n/p).subs(x, 1)), int):
print("This number is a prime!")
else:
print("It is not a prime")
I am trying to make a test for a prime number. (x-1)^p - (x^p - 1), if this is dividable by p and p != 1 then its a prime. My code is not quality because I am changing x to 1 , but I wanna check if it would work..
I think you're using evalf() incorrectly.
From what I've seen, it should be ((n/p).subs(x, 1)).evalf()
https://docs.sympy.org/latest/modules/evalf.html
It might be something else, but give it a try.
I'm writing a function in Python product_z which computes the product of
(N^z)/z * ∏ k/z+k from k=1 to N.
The code looks like this;
import numpy as np
def z_product(z,N):
terms = [k/(z+k) for k in range(1,N+1)]
total = (N^z/z)*np.prod(terms)
return total
However, I'm running the code with this input for example but I get a TypeError in return.
"Check that z_product returns the correct datatype."
assert type(z_product(2,7)) == np.float64 , "Return value should be a NumPy float."
print("Problem 2 Test 1: Success!")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-d2e9161f328a> in <module>()
1 "Check that z_product returns the correct datatype."
----> 2 assert type(z_product(2,7)) == np.float64 , "Return value should be
a NumPy float."
3 print("Problem 2 Test 1: Success!")
<ipython-input-8-1cd27b06388f> in z_product(z, N)
1 def z_product(z,N):
2 terms = [k/(z+k) for k in range(1,N+1)]
----> 3 total = (N^z/z)*np.prod(terms)
4 return total
TypeError: unsupported operand type(s) for ^: 'int' and 'float'
What am I doing wrong and how do I fix this to make the code run?
I think you're trying to exponentiate using the ^ operator. This is the proper operator in some languages (like R or MATLAB), but is not proper python syntax. In Python, the ^ operator stands for XOR. Use ** instead:
def z_product(z,N):
terms = [k/(z+k) for k in range(1,N+1)]
total = (N**z/z)*np.prod(terms)
return total
>>> z_product(2,7)
0.6805555555555555
Alternatively, you can use np.power intead:
def z_product(z,N):
terms = [k/(z+k) for k in range(1,N+1)]
total = (np.power(N,z)/z)*np.prod(terms)
return total
First of all: I am by no means a Python expert, so this question is probably rather easy. Secondly, I worked over more than 2 hours on this and now I've decided I needed help. I want to implement a distance in Python. The distance is given as follows:
Where ui and uj are vectors that are given. d is the dimension of that vector. For example: if ui = (1,2,3), then ui_0= 1.
Now, this is what I've come up with so far: (here, xi = ui and xj = uj)
def dist(xi, xj, k):
distances = np.zeros(len(xi))
min1 = (0, 0)
min2 = (0, 0)
for dim in [0, len(xi)]:
for s in [-k, k]:
min1 = abs(xi[dim] - xj[dim + s])
min1[-k, k].min()
min2 = min(abs(xj[dim] - xi[dim + s]))
min2[-k, k].min()
distances = max(min1,min2)
but it doesn't work. Does anybody know where I've gone wrong?
Traceback:
Traceback (most recent call last): File "<input>", line 1, in
<module> File "<input>", line 8, in dist IndexError: invalid index
to scalar variable.
EDIT:
Ok, I tried to look at the case where k is maximal and I've taken the comments of Riley and Wouda into account. I came up with this piece of code:
def dist1(xi, xj):
for dim in range(len(xi)):
for s in range(-dim, len(xi) - dim):
return max(min(abs(xi[dim] - xj[dim + s])), min(abs(xj[dim] - xi[dim + s])))
and I still get the error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 4, in dist1
TypeError: 'numpy.int64' object is not iterable
What is going on?
You appear to forget d is a parameter also (since you compute Dist_d^{ij}, where d is clearly a passed parameter). Together with k, I think the following represents the snippet of math you posted.
def dist(xi, xj, d, k):
min1 = min(abs(xi[d] - xj[d + s]) for s in range(-k, k + 1))
min2 = min(abs(xj[d] - xi[d + s]) for s in range(-k, k + 1))
return max(min1, min2)
Notice that Python will index negative values from the end of the list, which may or may not be what you want (in math, generally, not). So getting the arguments to this function right is a bit tricky, and you should build-in some checks to make sure all cases are handled correctly.
here is the python code.
from BitVector import *
MX = BitVector(bitstring = '00011011')
MSB_check = BitVector(bitstring = '10000000')
def multiplication_logic(num):
num = num.shift_left(1) # left shift
MSB_num = num & MSB_check # AND num with 1000 0000 to get only MSB
if MSB_num.intValue() != 0:
num = num ^ MX #XOR with 00011011
return num
for indexOfOneInPoly2 in range (0,7):
if polynomial_2[indexOfOneInPoly2] == 1 and indexOfOneInPoly2 != 0:
for numberOfIndexTimes in range (0,indexOfOneInPoly2):
temp = multiplication_logic(polynomial_1)
print(temp)
polynomial_3 = polynomial_3 + temp
print(polynomial_3)
For the above code I get the error
Traceback (most recent call last):
File "<pyshell#126>", line 4, in <module>
temp = multiplication_logic(polynomial_1)
File "<pyshell#124>", line 3, in multiplication_logic
MSB_num = num & MSB_check
TypeError: unsupported operand type(s) for &: 'NoneType' and 'BitVector'
How can I make my function take parameter as a BitVector (since this is what i think is creating the problem
It looks like the BitVector.shift_left() method returns None, presumably because the bit vector is mutated in place.
There is no need to re-assign num in this case, just use:
def multiplication_logic(num):
num.shift_left(1)
MSB_num = num & MSB_check # AND num with 1000 0000 to get only MSB
if MSB_num != 0:
num = num ^ MX #XOR with 00011011
return num
If you are using the BitVector package you'll need to upgrade to version 3.1 or newer (current release is 3.4.4), as that release added return self to the BitVector.shift_left() and BitVector.shift_right() methods.
From the project changelog:
Version 3.1:
This version includes: [....] (3) The non-circular bit shift methods now return self so that they can be chained;
from math import sqrt
def fermatBook (n):
x=int(sqrt(n))
c=x**2-n
while (sqrt(c)!=int(sqrt(c))):
x=x+1
y=sqrt(c)
a=x+y
b=x-y
if a==1 or b==1:
print "The number is prime"
return a, b
error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
fermatBook (23867)
File "C:/Python27/fermatLivro.py", line 6, in fermatBook
while (sqrt(c)!=int(sqrt(c))):
ValueError: math domain error
I don't know what is going wrong with the program... Could someone help me ?
most likely your variable c is going negative:
Example
if you call:
n = 2
fermatBook(n)
it will assign the following values to the following variables:
x = int(sqrt(n)) = int(1.47...) = 1
c = x**2 - n = 1**2 - 2 = 1 - 2 = -1
This will likely happen alot on values of n whose square root is not an integer.
sqrt(n) >= int(sqrt(n)), n >= 0
Then when you call sqrt(c) it is out of the domain because it cannot handle negative values.
>>> from math import sqrt
>>> sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
You should rather use something that can handle imaginary numbers, i.e. cmath
Or perform checks to assure this does not happen:
As an example...
if c < 0:
c = 0
As soon as you fix this however you are going to run into another problem:
This is an infinite loop:
while (sqrt(c)!=int(sqrt(c))):
x=x+1
you need to update c otherwise the condidtion will never change no matter how many times you increment x. You probably meant this?
while (sqrt(c)!=int(sqrt(c))):
x=x+1
c = x**2+n # <--- UPDATE c