Python 4 Engineers — More Exercises!

Another Round to Make Sure that Python is Really Amazing!— #PySeries#Episode 03

J3
Jungletronics
12 min readAug 30, 2020

--

This Python training will give you enough understanding of how Python 3 can be applied in solving engineering problems.

This is the extension of this post:

01 Episode #PySeries — Python — Python 4 EngineersExercises! An overview of the Opportunities Offered by Python in Engineering!

Let’s get it on!

01#PyEx — Python —Operational Costs:

The Problem: In January, a disposable cup industry had a cost of $ 27,936.10 for the purchase of raw materials and $ 1,243.90 for freight. Using Python, determine what was the total cost for purchasing the raw material?

Here is the solution:

raw=27936.10
freight=1243.90
total_cost = raw + freight
print('Total cost was: $%.2f' %total_cost)
Total cost was: $29180.00

02#PyEx — Python — Roots — Second-Degree Equation:

The Problem: Using Python, find the roots of the function y = 2x^2 + 10x-4:

Here is the solution:

import numpy as np
c=[2,10,-4]
np.roots(c)
array([-5.37228132, 0.37228132])

03#PyEx — Python — Break-Even Point:

The Problem: A company's revenue is given by R (x) = 314x and costs by C (x) = 179x + 10530 where x is the marketed quantity of a given product. Determine the respective break-even point using Python:

The solution:

from sympy import *
C,R,x=symbols("C R x")
init_printing()
R=314*x
C=179*x+10530
xp=solve(Eq(R,C),x)
yp=R.subs(x, xp[0])
print(xp[0])
print(yp)
78
24492

04#PyEx — Python —Polynomials :

The Problem: A frozen meat industry conducted a study and concluded that the monthly profit p (x) is given as a function of the price x per kilo of frozen meat and this relationship is described by the polynomial p(x)=-80x+7900x-5000. Determine for which values of x the monthly profit is zero:

The solution:

import numpy as np 
c=[-80,7900,-5000]
np.roots(c)
array([98.11297929, 0.63702071])

05#PyEx — Python —Factorization:

The Problem: Write the factored form of the expression x^2y^5 + 3x^3y^4-x^3y^6:

The solution:

from sympy import *
x,y = symbols("x y")
factor(x**2*y**5+3*x**3*y**4-x**3*y**6)
-x^2y^4(xy^2-3x-y)

06#PyEx — Python — 1ª Derivative:

The Problem: Calculate, using Python, the first derivative of each of the following functions: f(x)=2*x^5+23x^3=7x:

The solution:

from sympy import *
x,f=symbols("x f")
f=-2*x**5+23*x**3-7*x
diff(f,x, 2)
2x(69-20x^2)

07#PyEx — Python — Vectors:

The Problem: Given the vectors u = (7, 1, -9) and v = (3, -5, -4), calculate u.v and uXv:

The solution:

import numpy as np
u=np.array([[7,1,-9]])
v=np.array([[3,-5,-4]])
uv=np.inner(u,v)
uXv=np.cross(u,v)
print(uv)
print(uXv)
[[52]]
[[-49 1 -38]]

08#PyEx — Python — Regression Line:

The Problem: Obtain the regression line, using python, that best fits these points: A(3,6), B(4,4), C(7,11) and D(10,12):

The solution:

import numpy as np
import matplotlib.pyplot as pyp
from scipy import stats
x=np.array([3,4,7,10])
y=np.array([6,4,11,12])
a,b,correlation,p,error=stats.linregress(x,y)
print('Regression line: y=%.2fx+%.2f'% (a,b))
print('Correlation Coefficient: r=%.2f'% correlation)
plt.plot(x,y,'o',label='Original data')
f=a*x+b
plt.plot(x,f,'r',label='Regression Line')
plt.ylim(0, 15)
plt.legend()
plt.show()
Regression line: y=1.10x+1.65
Correlation Coefficient: r=0.90

09#PyEx — Python —Financial Math:

The Problem: Simple Interest: We can also calculate the amount, which is the total amount received or due, at the end of the time period. This value is the sum of the interest with initial value (principal).Your formula will be:M = C + J → M = C + C. i. tFrom the above equation, we therefore have the expression:M = C. (1 + i. t)For interest rate, we can use:M = C + C.i.t -> M - C = C.i.t -> i = (M-C)/(C.t), then multiply by 100 to have the percentage rate;If the $ 1,214.15 invoice was paid 19 days late for a total of $ 1,223.11, what is the daily interest rate used?

The solution:

C=1214.15
M=1223.11
t=19
i=(M-C)/(C*t)*100
print('The mensal daily is: %.5f %%'%i)
The mensal daily is: 0.03884 %

10#PyEx — Python —Equation Development :

The Problem: Using Python to evolve the equation: 
(12x^5-3x^4+4x^2)^2:

The solution:

from sympy import *
x,f= symbols("x f")
f=(12*x**5-3*x**4+4*x**2)**2
expand(f)
144x^10-72x^9+x^8+96x^7-24x^6+16x^4

11#PyEx — Python —Points Interpolation :

The Problem: Get through python the function that interpolates the points: A(3,6), B(4,4), C(7,11) and D(10,12):

The solution:

from scipy.interpolate import *
x=[3,4,7,10]
y=[6,4,11,12]
f=lagrange(x,y)
print(f)
-0.2024 x^3 + 3.917 x^2 - 21.93 x + 42

12#PyEx — Python —Linear Programming :

The Problem: Solve, using python, the linear programming problem:Maxz = 3x1 + 4x2 + 2*x31x1+10x2+4*x3 <= 1204x1+1x2 <= 802x2+3x3 <= 78

The solution:

from pulp import *
prob=LpProblem('Example', LpMaximize)
x1=LpVariable("Product A", 0)
x2=LpVariable("Product B", 0)
x3=LpVariable("Product C", 0)
prob += 3*x1 + 4*x2 + 2*x3
prob += 1*x1+10*x2+4*x3 <= 120
prob += 4*x1+1*x2 <= 80
prob += 2*x2+3*x3 <= 78
prob.solve()
for v in prob.variables():
print(v.name,"=", v.varValue)
print("Max Profit = ", value(prob.objective))
Product_A = 20.0
Product_B = 0.0
Product_C = 25.0
Max Profit = 110.0

13#PyEx — Python —Operational Costs:

The Problem: the expression that relates the cost c referring to the daily production of x units in an industry of motorcycles is given by the function c (x) = 2x^2+7x+9000; get the cost for 30 units:

The solution:

from sympy import *
x,y=symbols("x y")
y=2*x**2+7*x+9000
y.subs(x,30)
11010

14#PyEx — Python — Interest Rate:

The Problem: A car costs cash $64,700.00, but will be paid in 8 equal installments without interest; What is the value of each installment?

The solution:

c=64700
t=8
bill=c/t
print(bill)
8087.5

15#PyEx — Python —Electronics — Resistor x Current :

The Problem: A resistor has a voltage y as a function of the current x described by the equation f(x)=x^2+8x, make the graph to illustrate the behavior of the resistor:

The solution:

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0, 100, 100)
y=x**2+8*x
plt.plot(x,y)
plt.xlabel('Current')
plt.ylabel('Tension')
plt.show()

16#PyEx — Python —Vectors: :

The Problem: Given the vectors u = (3, -2, 1) and v = (6, 5, -7), calculate u.v:

The solution:

import numpy as np
u=np.array([[3,-2,1]])
v=np.array([[6,5,-7]])
uv=np.inner(u,v)
uXv=np.cross(u,v)
print(uv)
[[1]]

17#PyEx — Python — Operational Costs:

The Problem: The cost c for the daily production of x units of a certain product corresponds to c(x)=2x^2-40x+1000; What is the level of production that minimizes the cost?

The solution:

import numpy as np
c=[2,-40,1000]
np.roots(c)
array([10.+20.j, 10.-20.j])

18#PyEx — Python —Integral :

The Problem: Calculate the definite integral of the function f(x)=x^3+cos(x) in the range [0,2]:

The solution:

from sympy import *
x,f=symbols("x f")
init_printing()
f=x**3+cos(x)
integrate(f,(x,0,2))
sin(2)+4

19#PyEx — Python — Linear System:

The Problem: Using python, solve the following linear system:4x-3y+z=15x+y+3z=272x+3y-4z=31

The solution:

import numpy as np
A=np.array([[4,-3,1],[1,1,3],[2,3,-4]])
b=np.array([[15],[27],[31]])
x=np.linalg.solve(A, b)
print(x)
[[9.2345679 ]
[8.35802469]
[3.13580247]]

20#PyEx — Python —Equation Roots:

The Problem: Using Python, find the roots of the function f(x)=-2x^3+7x^2-20x+6.

The solution:

import numpy as np
c=[-2,7,-20,6]
np.roots(c)
array([1.58217509+2.53665299j, 1.58217509-2.53665299j,
0.33564982+0.j ])

21#PyEx — Python — Parabole:

The Problem: In a soccer match, an unusual move occurred: the goalkeeper, when shooting the goal, hit the ball inside the opponent's goal, the trajectory described by the ball was a parabola calculated by the f(x)=-0.008x^2+0.8x equation; Determine the total distance between the point where the ball was kicked and the point where it touches the ground:

The solution:

import numpy as np
c=[-0.008,0.8,0]
np.roots(c)
array([100., 0.])

22#PyEx — Python —Vectors :

The Problem: Given the vectors u = (3, -2, 1) and v = (6, 5, -7), calculate u.v and uXv:

The solution:

import numpy as np
u=np.array([[3,-2,1]])
v=np.array([[6,5,-7]])
uv=np.inner(u,v)
uXv=np.cross(u,v)
print(uv)
print(uXv)
[[1]]
[[ 9 27 27]]

23#PyEx — Python — Indefinite Integral:

The Problem: Calculate the indefinite integral of the function:f’(x) = x³+cos(x);

The solution:

from sympy import *
x,f=symbols("x f")
init_printing()
f=x**3+cos(x)
integrate(f,x)
x^4/4+sin(x)

24#PyEx — Python — Operational Costs:

The Problem: A company not opting for the simple Brazilian national (Super Simples), pays 68.18% of tax on the salary of each monthly employee and the total monthly cost referring to the wages plus tax of 12 employees, who receive the same salary, corresponds to $ 137,236.64. So what is the free salary for each of these employees?

The solution:

salaries=137236.64
tax=1.6818
employees=12
salary=(salaries)/(tax*employees)
print('The salary of each employees is: $ %.2f' %salary)
The salary of each employees is: $ 6800.09

25#PyEx — Python —2º Derivative :

The Problem: What is the second derivative of the function: f(x)=19x^6-33x^3+111x+19?

The solution:

from sympy import *
x,f=symbols("x f")
f=-19*x**6-33*x**3+111*x+19
expand(diff(f,x, 2))
-570x^4-198x

26#PyEx — Python — Integral — Area:

The Problem: Let the function be f(x)=-4x2^+40x-7; Obtain the area between the graph of f delimited by the x axis Make the graph:

The solution:

import matplotlib.pyplot as plt
import numpy as np
import sympy as sy
x,f=symbols("x f")
f=-4*x**2+40*x-7
A=integrate(f,(x))
x=np.linspace(-1,3,1000)
f=-4*x**2+40*x-7
plt.plot(x,f, color='blue')
plt.axhline(color='blue')
plt.fill_between(x,f, w
print('Area=', A)
Area= -4*x**3/3 + 20*x**2 - 7*x

27#PyEx — Python —Polynomials :

The Problem: Get the polynomials that interpolate the points: A(0,2), B(3,7) and C(10,-2):

The solution:

from scipy.interpolate import *
x=[0,3,10]
y=[2,7,-2]
f=lagrange(x,y)
print(f)
-0.2952 x^2 + 2.552 x + 2

28#PyEx — Python —Points Interpolation :

The Problem: Which is the line that interpolates the points: A(2,5) and B(7,10)?

The solution:

from scipy.interpolate import *
x=[2,7]
y=[5,10]
f=lagrange(x,y)
print(f)
1 x + 3

29#PyEx — Python —Operational Costs :

The Problem: In a bicycle factory, production in the third month of a certain year was 2,000 units and production in the sixth month was 3,000 units; Which is the line that interpolates these points (in thousands) ?

The solution:

from scipy.interpolate import *
x=[3,6]
y=[2000,3000]
f=lagrange(x,y)
print(f/1000)
0.3333 x + 1

30#PyEx — Python —Definite Integral :

The Problem: Calculate the definite integral of the function f(x)=5x^2+3x+1 in the range x=0 and x=4:

The solution:

from sympy import *
x,f=symbols("x f")
init_printing()
f=5*x**2+3*x+1
integrate(f,(x,0,4))
404/3
134.667

31#PyEx — Python — Linear Regression:

The Problem: The following table represents the sale of hospital equipment:1-1802-1203-1504-1905-210which line best line that fits these points?

The solution:

import numpy as np
import matplotlib.pyplot as pyp
from scipy import stats
x=np.array([1,2,3,4,5])
y=np.array([180,120,150,190,210])
a,b,correlation,p,error=stats.linregress(x,y)
print('Regression line: y=%.2fx+%.2f'% (a,b))
print('Correlation Coefficient: r=%.2f'% correlation)
plt.plot(x,y,'o',label='Original data')
f=a*x+b
plt.plot(x,f,'r',label='Regression Line')
plt.ylim(140, 200)
plt.legend()
plt.show()
Regression line: y=13.00x+131.00
Correlation Coefficient: r=0.58

32#PyEx — Python — 1ª Derivative:

The Problem: Calculate, using Python, the first derivative of each of the following functions: f(x)=18x^4-14x^2+22X-1:

The solution:

from sympy import *
x,f=symbols("x f")
f=-18*x**4-14*x**2+22*x-1
diff(f,x)
-72x^3-28x+22

33#PyEx — Python —Production Costs — Points Interpolations:

The Problem: In a bicycle factory, production in the third month of a certain year was 2,000 units and production in the sixth month was 3,000 units; What is the forecast for the seventh month?

The solution:

from scipy.interpolate import *
x=[3,6]
y=[2000,3000]
f=lagrange(x,y)
print(f/1000)
0.3333 x + 1
0.3333*7+1=3.3331

34#PyEx — Python — Linear Regression:

The Problem: A manager wants to find the relationship between the number of hours that a plant is operational in a week and weekly production. Here the independent variable x is hours of operation, and the dependent variable y is production volume. The manager develops the following table:x - y34 - 10235 - 10439 - 13742 - 14843 - 15047 - 158production Hour (x) - Production Volume (y)

The solution:

from scipy.stats import linregress
x=[34,35,39,42,43,47]
y=[102,109,137,148,150,158]
slope=round(linregress(x,y).slope,1)
intercept=round(linregress(x,y).intercept,1)
print(f'y={intercept} + {slope}')
y=-46.0 + 4.5

Alternative Solution:

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
x=np.array([34,35,39,42,43,47])
y=np.array([102,109,137,148,150,158])
a,b,correlation,p,error=stats.linregress(x,y)
print('Regression line: y=%.2fx+%.2f'% (a,b))
print('Correlation Coefficient: r=%.2f'% correlation)
plt.plot(x,y,'o',label='Original data')
f=a*x+b
plt.plot(x,f,'r',label='Regression Line')
plt.ylim(100, 180)
plt.legend()
plt.show()
Regression line: y=4.50x+-46.00
Correlation Coefficient: r=0.97

And finally, that’s all!

I hope you can be as surprised just as I am surprised by the 💪Power of Python!

See you in next PySeries!

Bye, for now, o/

Download all Files from the GitHub Repo

References & Credits

Thank you, Mr. Ricardo A. Deckmann Zanardini — You are an Awesome Teacher! o/; Text edited while I’m studying Computer Engineer at Escola Superior Politécnica Uninter🏋!

Posts Related:

00Episode#PySeries — Python — Jupiter Notebook Quick Start with VSCode — How to Set your Win10 Environment to use Jupiter Notebook

01Episode#PySeries — Python — Python 4 Engineers — Exercises! An overview of the Opportunities Offered by Python in Engineering!

02Episode#PySeries — Python — Geogebra Plus Linear Programming- We’ll Create a Geogebra program to help us with our linear programming

03Episode#PySeries — Python — Python 4 Engineers — More Exercises! — Another Round to Make Sure that Python is Really Amazing! (this one)

04Episode#PySeries — Python — Linear Regressions — The Basics — How to Understand Linear Regression Once and For All!

05Episode#PySeries — Python — NumPy Init & Python Review — A Crash Python Review & Initialization at NumPy lib.

06Episode#PySeries — Python — NumPy Arrays & Jupyter Notebook — Arithmetic Operations, Indexing & Slicing, and Conditional Selection w/ np arrays.

07Episode#PySeries — Python — Pandas — Intro & Series — What it is? How to use it?

08Episode#PySeries — Python — Pandas DataFrames — The primary Pandas data structure! It is a dict-like container for Series objects

09Episode#PySeries — Python — Python 4 Engineers — Even More Exercises! — More Practicing Coding Questions in Python!

10Episode#PySeries — Python — Pandas — Hierarchical Index & Cross-section — Open your Colab notebook and here are the follow-up exercises!

11Episode#PySeries — Python — Pandas — Missing Data — Let’s Continue the Python Exercises — Filling & Dropping Missing Data

12Episode#PySeries — Python — Pandas — Group By — Grouping large amounts of data and compute operations on these groups

13Episode#PySeries — Python — Pandas — Merging, Joining & Concatenations — Facilities For Easily Combining Together Series or DataFrame

14Episode#PySeries — Python — Pandas — Pandas Dataframe Examples: Column Operations

15Episode#PySeries — Python — Python 4 Engineers — Keeping It In The Short-Term Memory — Test Yourself! Coding in Python, Again!

16Episode#PySeries — NumPy — NumPy Review, Again;) — Python Review Free Exercises

17Episode#PySeriesGenerators in Python — Python Review Free Hints

18Episode#PySeries — Pandas Review…Again;) — Python Review Free Exercise

19Episode#PySeriesMatlibPlot & Seaborn Python Libs — Reviewing theses Plotting & Statistics Packs

20Episode#PySeriesSeaborn Python Review — Reviewing theses Plotting & Statistics Packs

--

--

J3
Jungletronics

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Ruby, Rails, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!