I am trying to make an iOS app that will calculate pi to a set about of decimal places based on what the user wants. I currently have a python script that will take in an integer value from the user and then use that in the calculation of Pi. I also have a swift/Xcode project that will only allow a user to input an integer value. So I am wondering if there is a way for me to pass this value that the user enters from a textbox in my swift project to then give that to the python code, run it, and then output the result? In my python code, I am using "timer" to be able to calculate the time it takes to calculate pi to the set digits that was requested. So I would only need to be able to display this result.
I have thought about rewriting the python script into swift, but I am unsure of how to do that. This is the definition I am using in my python script to calculate pi:
def pi():
decimal.getcontext().prec += 2
three = decimal.Decimal(3)
first, second, third, forth, fifth, sixth, numb = 0, three, 1, 0, 0, 24, 3
while numb != first:
first = numb
third, forth = third + forth, forth + 8
fifth, sixth = fifth + sixth, sixth + 32
second = (second * third) / fifth
numb += second
decimal.getcontext().prec -= 2
return +numb
But I was unsure of how to rewrite this into swift language, so I figured getting swift to pass the precision value into python would be easier.
You definitely can run Python code in Swift since Python is designed to be embedded and has a C interface API. Check how Swift for TensorFlow uses Python interoperability (although I couldn't find a quick way to only use that module and not the whole TensorFlow). You can also check PythonKit out.
However, I don't think rewriting that script would be too difficult, and it might be better to avoid more libraries and dependencies in your project.
Edit: As Joakim Danielson pointed out, you'll need the Python runtime, and it doesn't seem to be available in iOS, so you seem to be limited to macOS for this.
Related
This is an old problem as is demonstrated as in https://community.intel.com/t5/Analyzers/Unable-to-view-source-code-when-analyzing-results/td-p/1153210. I have tried all the listed methods, none of them works, and I cannot find any more solutions on the internet. Basically vtune cannot find the custom python source file no matter what is tried. I am using the most recently version as of speaking. Please let me whether there is a solution.
For example, if you run the following program.
def myfunc(*args):
# Do a lot of things.
if __name__ = '__main__':
# Do something and call myfunc
Call this script main.py. Now use the newest vtune version (I have using Ubuntu 18.04), run the vtune-gui and basic hotspot analysis. You will not found any information on this file. However, a huge pile of information on Python and its other codes are found (related to your python environment). In theory, you should be able to find the source of main.py as well as cost on each line in that script. However, that is simply not happening.
Desired behavior: I would really like to find the source file and function in the top-down manual (or any really). Any advice is welcome.
VTune offer full support for profiling python code and the tool should be able to display the source code in your python file as you expected. Could you please check if the function you are expecting to see in the VTune results, ran long enough?
Just to confirm that everything is working fine, I wrote a matrix multiplication code as shown below (don't worry about the accuracy of the code itself):
def matrix_mul(X, Y):
result_matrix = [ [ 1 for i in range(len(X)) ] for j in range(len(Y[0])) ]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result_matrix[i][j] += X[i][k] * Y[k][j]
return result_matrix
Then I called this function (matrix_mul) on my Ubuntu machine with large enough matrices so that the overall execution time was in the order of few seconds.
I used the below command to start profiling (you can also see the VTune version I used):
/opt/intel/oneapi/vtune/2021.1.1/bin64/vtune -collect hotspots -knob enable-stack-collection=true -data-limit=500 -ring-buffer=10 -app-working-dir /usr/bin -- python3 /home/johnypau/MyIntel/temp/Python_matrix_mul/mat_mul_method.py
Now open the VTune results in the GUI and under the bottom-up tab, order by "Module / Function / Call-stack" (or whatever preferred grouping is).
You should be able to see the the module (mat_mul_method.py in my case) and the function "matrix_mul". If you double click, VTune should be able to load the sources too.
To test my Verilog design I'm using two differents simulators : Icarus and Verilator. It's work, but there are some variations between them.
For example, I can't read module parameter with verilator, but Icarus works.
Is there a way to know which simulator is in use in python testfile ?
I would like to write something like that :
if SIM == 'icarus':
self.PULSE_PER_NS = int(dut.PULSE_PER_NS)
self.DEBOUNCE_PER_NS = int(dut.DEBOUNCE_PER_NS)
else:
self.PULSE_PER_NS = 4096
self.DEBOUNCE_PER_NS = 16777216
To be able to manage both simulator and compare them.
The running simulator name (as a string) can be determined using cocotb.SIM_NAME. If cocotb was not loaded from a simulator, it returns None.
I’m currently developing a script using the python script editor in Rhino. As I’m currently working in a Windows machine, the script editor uses IronPython as language.
In the same script, I want to interact with an FE software (Straus7) which has a Python API. When doing so, I have experienced some problems as the ctypes module does not seem to work in IronPython the same way it does in regular Python. Especially, I’m finding problems when initializing arrays using the command:
ctypes.c_double*3
For example, if I want to obtain the XYZ coordinates of a node #1 in the FE model, I regular Python I would write the following:
XYZType = ctypes.c_double*3
XYZ = XYZType()
node_num = 1
st.St7GetNodeXYZ(1,node_num,XYZ)
And this returns me a variable XYZ which is a 3D array such that:
XYZ -> <straus_userfunctions.c_double_Array_3 at 0xc5787b0>
XYZ[0] = -0.7xxxxx -> (X_coord)
XYZ[1] = -0.8xxxxx -> (Y_coord)
XYZ[2] = -0.9xxxxx -> (Z_coord)
On the other side, I copy the same exact script in IronPython, the following error message appears
Message: expected c_double, got c_double_Array_3
Obviously, If I change the variable XYZ to c_double; then it becomes a double variable which contains only a single entry, which corresponds to the first element of the array (in this case, the X-coordinate)
This situation is quite annoying as all FEM softwares, the usage of matrices and arrays is widely used. Consequently, I wanted to ask if anyone nows a simple fix to this situation.
I was thinking of using the memory allocation of the first element of the array to obtain the rest but I’m not so sure how to do so.
Thanks a lot. Gerard
I've found when working with IronPython you need to explicitly cast the "Array of three doubles" to a "Pointer to double". So if you're using Grasshopper with the Strand7 / Straus7 API you will need to add an extra bit like this:
import St7API
import ctypes
# Make the pointer conversion functions
PI = ctypes.POINTER(ctypes.c_long)
PD = ctypes.POINTER(ctypes.c_double)
XYZType = ctypes.c_double*3
XYZ = XYZType()
node_num = 1
# Cast arrays whenever you pass them to St7API from IronPython
St7API.St7GetNodeXYZ(1, node_num, PD(XYZ))
I don't have access to IronPython or Strand7 / Straus7 at the moment but from memory that will do it. If that doesn't work for you you can email Strand7 Support - you would typically get feedback on something like this within a day or so.
I know there are possibilities :
sampleword[::-1]
or
reverse(string)
but I wanted to write it by myself. I don't get why my code doesn't work. Could you help me?
h=input('word\n\n');
rev(h)
def rev(h):
counter=len(h);
reverse="";
while counter>0:
reverse+=h[counter];
counter=counter-1;
return reverse
#print (reverse); ?
input();
There are a couple issues with your code, I pointed them out in the comments of this adjusted script:
def rev(h):
counter=len(h) - 1 # indexes of h go from 0 to len(h) - 1
reverse=""
while counter>=0: # changed to >=0
reverse+=h[counter]
counter -= 1
return reverse
h=input('word\n\n');
revers = rev(h) # put rev(h) after the definition of rev!
print(revers) # actually print the result
# deleted your last line
In addition, you don't need to terminate lines with ; in python and you can write counter=counter-1 as counter -= 1.
You have some issues/problems in your code.
You call rev() before it is defined
Indexing starts at 0, so you need >= 0 instead of > 0
You want counter to equal len(h) - 1 because again, indexing starts at 0
You do not need semicolons at the end of your lines
Here is a much simpler and faster way using recursion:
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
As you use Python more you will come across the concept of "Pythonic" code ... code that uses Python features well and shows good programming style.
So, you have a good answer above showing how your code can be corrected to work correctly in Python. But the issue I want to point out is that's C style programming. Someone said you can write C in any language (especially true in C++ and C#), but if you do you are probably not using the features of the language well. In Python, writing this style of function and ignoring the available built-in, implemented in C, lightning fast methods is not Pythonic.
I guarantee you that reverse(string) or string[::-1] are both faster than your rev( ) python code. Python has a ton of built in functionality and extensive library of files you can import for extra already debugged functionality. See if you can find a good way to time the execution of reverse( string ) and your rev( ) function. There is a good way, in Python.
The Python tutorial book I'm using is slightly outdated, but I've decided to continue using it with the latest version of Python to practice debugging. Sometimes there are a few things in the book's code that I learn have changed in the updated Python, and I'm not sure if this is one of them.
While fixing a program so that it can print longer factorial values, it uses a long int to solve the problem. The original code is as follows:
#factorial.py
# Program to compute the factorial of a number
# Illustrates for loop with an accumulator
def main():
n = input("Please enter a whole number: ")
fact = 1
for factor in range(int(n), 0, -1):
fact = fact * factor
print("The factorial of ", n, " is ", fact)
main()
The long int version is as follows:
#factorial.py
# Program to compute the factorial of a number
# Illustrates for loop with an accumulator
def main():
n = input("Please enter a whole number: ")
fact = 1L
for factor in range(int(n), 0, -1):
fact = fact * factor
print("The factorial of ", n, " is ", fact)
main()
But running the long int version of the program in the Python shell generates the following error:
>>> import factorial2
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
import factorial2
File "C:\Python34\factorial2.py", line 7
fact = 1L
^
SyntaxError: invalid syntax
Just drop the L; all integers in Python 3 are long. What was long in Python 2 is now the standard int type in Python 3.
The original code doesn't have to use a long integer either; Python 2 switches to the long type transparently as needed anyway.
Note that all Python 2 support is shortly ending (no more updates after 2020/01/01), so at this point in time you'd be much better of switching tutorials and invest your time in learning Python 3. For beginner programmers I recommend Think Python, 2nd edition as it is fully updated for Python 3 and freely available online. Or pick any of the other Stack Overflow Python chatroom recommended books and tutorials
If you must stick to your current tutorial, you could install a Python 2.7 interpreter instead, and work your way through the book without having to learn how to port Python 2 to Python 3 code first. However, you'd then also have to learn how transition from Python 2 to Python 3 in addition.
You just need remove L
fact = 1
Python 3.X integers support unlimited size in contrast to Python 2.X that has a separate type for long integers.