How to copy source code (for Python) into text mate : - python-3.x

Taking my first programming course in python. Instructions were to: Copy and paste your assembly language source code into your processor document. Using textmate as my processor document. Not sure how source code is supposed to look. This is what I have :
Objective: Calculate the area of a triangle
>>> base=4
>>> height=3
>>> area=1.0/2.0 * base* height
>>> print("Area is:", area)
Area is: 6.0
Is this accurate? I just copied and pasted what I got when I ran it in IDLE for Python

Your code is accurate - for the formula for a triangle, you should know is:
A = (1/2)*b *h
Therefore the math is correct, henceforth your code is correct. Now - a simpler way to do this is:
base, height = 4, 3
area=1/2 * base* height
print("Area is:", area)
With python, you can define 2 or more variables on one line, as long as both sides have equal parts.
For Example:
base, height, width = 4, 3, 2
Having it this way, saves space and is useful for when you want to have return statements in your functions.
def main(inp): # For this example we r going to use strings for simplicity sake.
return inp, inp + "1", inp + "2", inp + "3"
# We return 4 values on one line, where as we cannot use 4 lines of
# return because python will give us an Error
print(main("hello"))
Functions and Classes are part of OOP Programming Btw
See you next time you post,
Jerry

Related

Changing printing format for fractions using sympy and PythonTex

Below is a minimal working problem, of what I am working on.
The file is a standard LaTeX file using sympy within pythontex, where I want to change
how sympy displays fractions.
Concretely I would like to make the following changes, but have been struggling:
How can I make sympy display the full, and not inline version of it's fractions for some of its fractions? In particular I would like the last fraction 1/5 to instead be displayed in full.
eg. \fraction{1}{5}
In the expression for the derivative, I have simplified the results, but I struggle to substitute the variable x with the fraction a/b. Whenever I substitute this expression into the fraction it fully simplifies the expression, which is not what I want. I just want to replace x with the fraction a/b (in this case 2/3 or 1/3 depending on the seed).
Below I have attached two images displaying what my code produces, and what I would like it to display. Do note that this is also stated in the two bullets above
Current output
Desired output
Code
\documentclass{article}
\usepackage{pythontex}
\usepackage{mathtools,amssymb}
\usepackage{amsmath}
\usepackage{enumitem}
\begin{document}
\begin{pycode}
import math
from sympy import *
from random import randint, seed
seed(2021)
\end{pycode}
\paragraph{Oppgave 3}
\begin{pycode}
a, b = randint(1,2), 3
ab = Rational(a,b)
pressure_num = lambda x: 1-x
pressure_denom = lambda x: 1+x
def pressure(x):
return (1-x)/(1+x)
pressure_ab = Rational(pressure_num(ab),pressure_denom(ab))
x, y, z = symbols('x y z')
pressure_derivative = simplify(diff(pressure(x), x))
pressure_derivative_ab = pressure_derivative.xreplace({ x : Rational(a,b)})
\end{pycode}
The partial pressure of some reaction is given as
%
\begin{pycode}
print(r"\begin{align*}")
print(r"\rho(\zeta)")
print(r"=")
print(latex(pressure(Symbol('\zeta'))))
print(r"\qquad \text{for} \ 0 \leq \zeta \leq 1.")
print(r"\end{align*}")
\end{pycode}
%
\begin{enumerate}[label=\alph*)]
\item Evaluate $\rho(\py{a}/\py{b})$. Give a physical interpretation of your
answer.
\begin{equation*}
\rho(\py{a}/\py{b})
= \frac{1-(\py{ab})}{1+\py{ab}}
= \frac{\py{pressure_num(ab)}}{\py{pressure_denom(ab)}}
\cdot \frac{\py{b}}{\py{b}}
= \py{pressure_ab}
\end{equation*}
\end{enumerate}
The derivative is given as
%
\begin{pycode}
print(r"\begin{align*}")
print(r"\rho'({})".format(ab))
print(r"=")
print(latex(pressure_derivative))
print(r"=")
print(latex(simplify(pressure_derivative_ab)))
print(r"\end{align*}")
\end{pycode}
\end{document}
Whenever I substitute this expression into the fraction it fully simplifies the expression, which is not what I want. I just want to replace x with the fraction a/b (in this case 2/3 or 1/3 depending on the seed).
It's possible to do this, if we use a with expression to temporarily disable evaluation for that code block, and then we use two dummy variables in order to represent the fraction, and finally we do the substitution with numerical values.
So the following line in your code:
pressure_derivative_ab = pressure_derivative.xreplace({ x : Rational(a,b)})
can be changed to:
with evaluate(False):
a1,b1=Dummy('a'),Dummy('b')
pressure_derivative_ab = pressure_derivative.subs(x,a1/b1).subs({a1: a,b1: b})
The expressions pressure_derivative and pressure_derivative_ab after this are:
How can I make sympy display the full, and not inline version of it's fractions for some of its fractions? In particular I would like the last fraction 1/5 to instead be displayed in full. eg. \fraction{1}{5}
For this, you only need to change this line:
= \py{pressure_ab}
into this line:
= \py{latex(pressure_ab)}
Because we want pythontex to use the sympy latex printer, instead of the ascii printer.
To summarize, the changes between the original code and the modified code can be viewed here.
All the code in this post is also available in this repo.

SolverStudio how to reference 1 column in a 2D list in a for loop(PuLP)

I have 2 data sets x1 and x2. I want to be able to get a total sum of all the products of x1 and x2 only in the rows where the From column has Auckland in it.
see here
The final answer should be (5*1) + (2*1) + (3*1) + (4*1) or 14. The PuLP code that I wrote to do this is given below
# Import PuLP modeller functions
from pulp import *
varFinal = sum([x1[a] * x2[a] for a in Arcs if a == Nodes[0]])
print Nodes[0]
print Arcs[0]
Final = varFinal
The output that gets printed to the console is
Auckland
('Auckland', 'Albany')
I realise that my final value is zero because Arcs[some number] does not equal Nodes[some number]. Is there anyway to change the code so my final value is 14?
Any help is appreciated.
Welcome to stack overflow! Cause you've only posted part of your code, I have to guess at what data-types you're using. From the output, I'm guessing your Nodes are strings, and your Arcs are tuples of strings.
Your attempt is very close, you want the from column to have Auckland in it. You can index into a tuple the same way you would into an array, so you want to do: a[0] == Nodes[0].
Below is a self-contained example with the first bit of your data in which outputs the following (note that I've changed to python 3.x print statements (with parentheses)):
Output:
Auckland
('Auckland', 'Albany')
14
Code:
# Import PuLP modeller functions
from pulp import *
# Data
Nodes = ['Auckland',
'Wellington',
'Hamilton',
'Kansas City',
'Christchuch',
'Albany',
'Whangarei',
'Rotorua',
'New Plymouth']
Arcs = [('Auckland','Albany'),
('Auckland','Hamilton'),
('Auckland','Kansas City'),
('Auckland','Christchuch'),
('Wellington','Hamilton'),
('Hamilton','Albany'),
('Kansas City','Whangarei'),
('Christchuch','Rotorua')]
x1_vals = [1, 2, 3, 4, 5, 9, 11, 13]
x2_vals = [5, 1, 1, 1, 1, 1, 1, 1]
x1 = dict((Arcs[i], x1_vals[i]) for i in range(len(Arcs)))
x2 = dict((Arcs[i], x2_vals[i]) for i in range(len(Arcs)))
varFinal = sum([x1[a] * x2[a] for a in Arcs if a[0] == Nodes[0]])
print(Nodes[0])
print(Arcs[0])
print(varFinal)
For future reference, answers are most likely to be forthcoming if you include code which others can try to run (without external data dependencies), that way people can try to run it, fix it, and re-post it.

how to display numbers in scientific notation in plot legends in Matlab?

I have two float variables, let's say they are phi = 1.34e8 and beta = -2.7e-6. How do I display both results in a plot label in latex scientific notation over two lines? I want the plot label to look like (in latex font):
\phi = 1.34 x 10^8
\beta = -2.7 x 10^-6
And what about I have other variables for error, e.g. phi_err = 7.1e7, and I want the legend to look like:
\phi = (1.34 +/- 0.71) x 10^8
Edit:
My current Matlab code:
txt1 = texlabel(['n2=',num2str(n2)]);
txt2 = texlabel(['beta=',num2str(beta)]);
figure(1)
plot(...)
text(0.7,0.8,{txt1,txt2},'Units','normalized')
And the plot text looks like the upper part of the attached figure. How do I display the text in scientific notation with the multiply sign and the base 10 instead of e? Also, if I want to add the error (let's say I set in Matlab beta=[-2.7e-6, 1.2e-6] where beta(1) is the value and beta(2) is the error), then show should I modify the above code so that the result looks like the lower part of the attached figure? For the example I give, how do I extract 2.7 and 1.2 before the e? And what if they are of different order of magnitude, e.g. the error is 1.2e-7, which means in the displayed text I have to change it from 1.2e-7 to 0.12e-6 and combine the error and the beta value.

Extremely Basic Python Program Doesn't Return Proper Value

I'm writing a very simple program that calculates how far an object has fallen due to gravity given how long it's been in the air.
(main.py)
# Importing falling_distance function
from a3_functions import falling_distance
# Doc-string
import a3_functions; print(a3_functions.falling_distance.__doc__)
# Input from user and formatted output
t = input('Enter the time (in secs): ')
print("The Object has fallen {:.2f} in {:d} seconds".format(falling_distance(t), t))
^^ Being the main module/class where the user puts in the amount of time. After that it references the program a3_functions.py which is essentially a library for various functions.
(a3_functions.py)
def falling_distance (t):
"""-------------------------------------------------------------------------
Purpose: Calculate and output falling distance (in metres) given time (in
seconds)
---------------------------------------------------------------------------
Preconditions:
t - time (int > 0)
g - gravitational constant
Postconditions:
returns:
d - distance (float > 0)
---------------------------------------------------------------------------
"""
t = int(t)
g = 9.8
d = (1/2)*g*t**2
return d
I know i can do it very simply in one program but can anyone tell me when d is being returned as 0?
In my opinion, i think it has something to do with the way eclipse is set up because it worked before. I worked on other programs, came back to this one and it broke. I feel like this is a simple problem that happens way too often and has an easy fix
You are using Python 2, not Python 3. They are often both installed on the same computer, and on most systems the default is 2 instead of 3. If you explicitly start it with python3 instead of just python, you should be able to get Python 3 if it’s installed.
Specifically, in Python 2, if you divide two integers, it converts the result to an integer, so 1/2 gives 0. This was changed to do floating-point division in Python 3.
Additionally, the input function in Python 2 is equivalent to eval(input(...)) in Python 3, so t is already an int. In Python 3, your format call doesn’t work because you can’t use {:d} on a string.

Knuth–Morris–Pratt algorithm: border array

Here is a pseudo code for computing the border array in KMP.
p is the pattern
border[1]:=-1
i:=border[1]
for j=2,...,m
while i >= 0 and p[i+1] != p[j-1] do i = border[i+1]
i++
border[j]:=i
I can execute the following pseudo code to compute the border array but the problem I am having right now is that I don't really understand the border array meaning how to interpret it.
For instance if the pattern does not equal at position (i+1) and (j-1) the variable i is set to border[i+1]. Why is that for example?
I realized the missing understanding when I tried to answer the question that three consecutive entries in a border array cannot differ by one from its predecessor. E.g. border[10]=3, border[11]=2, border[12]=1
I would appreciate a good explanation in order to get a better understanding.
What you call the border array is the prefix function.
There are many explanations, see Stackoverflow, Wikipedia, or just google an explanation more suitable for you.
As for the second part of your question, the following string is an example for the property you ask for:
column: 0123456
string: abcabac
border: 0001210
Here, border[4] = 2 because ab = ab, border[5] = 1 because a = a, and border[6] = 0.
Whether all three values can be non-zero (for example, 3, 2, 1) is an interesting question.

Resources