Python 4 Engineers — Exercises!

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

J3
Jungletronics
9 min readAug 6, 2020

--

Hi, here are some exercises to start to see problems solutions issues things from another perspective: Python is a fantastic sci_tool! Check it out!

01#PyEx — Python — Mechanical Tolerance:

The Problem: A hole has a diameter of 80mm and a tolerance of -0.102 and +0.222. Determine the minimum and maximum dimensions of this hole using Python Jupiter Notebook:)

Fig 1. First problem illustration; If you have no Jupyter yet, please, considering following this tutorial :)
01_Solution (python cell code):D=80
a=-0.102
b=0.222
Dmin=D+a
Dmax=D+b
print('Max Diameter: %.3f' % Dmax)
print('Min Diameter: %.3f' % Dmin)
Max Diameter: 80.222
Min Diameter: 79.898
Fig 2. Solution: Max Diameter: 80.222 Min Diameter: 79.898

02#PyEx — Python — Compound Rate: In the compound interest modality, the future value is calculated using the formula:

vf = vp * (1 + i) ** n

Where vf is the future value, vp is the present value, i the growth rate and n is the elapsed time;

The Problem: What is the future value of a $ 144,010 investment made in 14 months at a compound interest rate of 1.3% per month?

02_Solution (python cell code):c=144010.00 
n=14
i=1.3/100
m=c*(1+i)**n
print('The amount is: $ %.2f' %m)
The amount is: $ 172553.94
Fig 3. Solution: The amount is: $ 172553.94

03#PyEx — Python — Roots of a Function:

The Problem: What are the roots of the function: f(x) = -2x³+7x²-20x + 6?

03_Solution (python cell code):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 ])
Fig 4. oops:/ The ModuleNotFoundError — Please, TO FIX IT, in console, type: pip install numpy
Fig 5. Run the cell again and there you have it! Solution: array([1.58217509+2.53665299j, 1.58217509–2.53665299j, 0.33564982+0.j ]); j is the imaginary part; note that in the third root we have only the real part; while studying quaternions to play in Unity, I understand what complex numbers are \o/ so please consider watching this video too: https://youtu.be/d4EgbgTm0Bg from 3Blue1Brown:)

04#PyEx — Python — Tables and Graphs: The following table 1 shows the number of downloads of an application from January to May of the year 2020.

table 1. App Downloads per Month

The Problem: Using python make a graph of lines with circles for each month related to the number of downloads with each of these months;

04_Solution (python cell code):import matplotlib.pyplot as plt
x=['Jan', 'Feb', 'Mar','Apr', 'May']
y=[127000, 133000, 129000, 134000, 136000]
plt.plot(x,y)
plt.plot(x,y,'r o')
plt.title("Downloads - From January to May")
plt.xlabel('Month')
plt.ylabel('Downloads')
plt. show()
graphic below
Fig 6. oops:/ there is no matplotlib installed; TO FIX IT, type this at console: pip install matplotlib
Fig 7. Run the cell again and there you have it! \o/

05#PyEx — Python — Pie charts:

The Problem: At McDonald’s international snack chain (the biggest fast-food company in the world), here in Brazil, has sold monthly online over 5226 BigMac, 2404 McSpicy, 3218 Cheeseburger, and 4321 McNuggets;

Fig 8. McDonald’s snacks menu \o/

Find Percentage of each product, and show results in a Pie Chart; highlighting the best selling snack of this month; use python, please:)

05_Solution (python cell code):import matplotlib.pyplot as plt
x=[5226,2404,3218,4321]
snacks=['BigMac','McSpicy','Cheeseburger','McNuggets']
colors=['r','m','y','g']
plt.axis('equal')
plt.pie(x,labels=snacks,colors=colors,shadow=True,explode=
(0.1,0,0,0),autopct=('%1.1f%%'))
plt.title('Snacks sold in a month')
plt.show()
graphic below
Fig 9. Running 05_Solution: McDonald’s pie o/

06#PyEx — Python — Derivatives: Derivatives can be used to calculate the profit and loss in business using graphs; to check the temperature variation; to determine the speed or distance covered such as miles per hour, kilometer per hour, to run Lego, Arduino, etc.

The Problem: Using python, calculate the first derivative of the function: f(x)=4x³+12x-7:

06_Solution (python cell code):from sympy import *
x,f=symbols("x f")
init_printing()
f=4*x**3+12*x-7
diff(f,x)
12x²+12
Fig 10. oops:/ there is no such thing as sympy! TO FIX IT, type this at the console: pip install sympy
Fig 11. Run the cell again and there you go! f`(x)=12x²+12 is the first derivative of the function f(x)=4x³+12x-7:)

07#PyEx — Python: Indefinite Integral or Antiderivatives — In calculus, an antiderivative, inverse derivative, primitive function, primitive integral, or indefinite integral of a function f is a differentiable function F whose derivative is equal to the original function f. This can be stated symbolically as {\displaystyle F’=f}; The process of solving for antiderivatives is called antidifferentiation (or indefinite integration) and its opposite operation is called differentiation, which is the process of finding a derivative (from https://en.wikipedia.org/wiki/Antiderivative).

The Problem: Calculate the indefinite integral of the function:

f’(x) = 4x³+12x+7;

07_Solution (python cell code):from sympy import *
x,f=symbols("x f")
init_printing()
f=4*x**3+12*x-7
integrate(f,x)
x⁴+6X²-7
Fig 12. Calculating the indefinite integral of the function f’(x) = 4x³+12x-7 which results in f(x)=x⁴+6X²-7

08#PyEx — Python — Linear System:

The Problem: Using python, solve the following linear system:

  • 5x+y+3z=76
  • -x+2y+5z=35
  • 4x-5y+z=22

Edited: April2021 (Python3 adaptation; )

08_Solution (python cell code):import numpy as np
A = np.array([[5, 1, 3], [-1, 2, 5], [4, -5, 1]])
b = np.array([76, 35, 22])
x = np.linalg.solve(A,b)
print(x)
[10. 5. 7.]
Fig 13. The results of the above linear system: [10. 5. 7.]

09#PyEx — Python — break-even point (BEP) in Economics:

Fig 14. BEP

The break-even point (BEP) in economics, business — and specifically cost accounting — is the point at which total cost and total revenue are equal, i.e. “even”. There is no net loss or gain, and one has “broken even”, though opportunity costs have been paid and capital has received the risk-adjusted, expected return. In short, all costs that must be paid are paid, and there is neither profit nor loss:/

The Problem: A company that produces honeycomb polycarbonate has a production cost of $ 129 per unit. Knowing that the sale of the product is $ 193.57 and the monthly production cost is $ 18322.80, obtain, using python, the BEP (I’ll use R for total Revenue, C for total Cost, x for Units sold, xp — x-axisfor the number of products sold to reach BEP point and yp — y-axis — for BEP point in $).

Fig 15. honeycomb polycarbonate sheet
09_Solution (python cell code):from sympy import *
C,R,x=symbols("C R x")
init_printing()
R=193.57*x
C=129*x+18322.80
xp=solve(Eq(R,C),x)
yp=R.subs(x, xp[0])
print(xp[0])
print(yp)
283.766455010067
54928.6726962986
Fig 16. The results of the above the break-even point (BEP) equation is 283.766455010067 and 54928.6726962986; which means that the company has to sell 284 products and the revenue will be balanced when the total revenue is $ 54929:)

10#PyEx — Python — Linear regression: Linear regression is a common Statistical Data Analysis technique. It is used to determine the extent to which there is a linear relationship between a dependent variable and one or more independent variables. The equation has the form Y= a + bX, where Y is the dependent variable (that’s the variable that goes on the Y-axis), X is the independent variable (i.e. it is plotted on the X-axis), b is the slope of the line and a is the y-intercept.

The Problem: The energy consumption in a residence is shown in table 2 below:

Table 2 — energy consumption

The Problem: Obtain, via python, the regression line, the correlation coefficient, and plot the graph showing the line and the data:

10_Solution (python cell code):import numpy as np
import matplotlib.pyplot as pyp
from scipy import stats
x=np.array([1,2,3,4,5,6])
y=np.array([134,126,141,145,139,142])
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(110, 160)
plt.legend()
plt.show()
Regression line: y=2.37x+129.53
Correlation Coefficient: r=0.65
graphic below
Fig 17. oops:/ Where is the scipy lib? There is no such a lib. TO FIX IT, type this at the console: pip install scipy
Fig 18. And there you have it! Congratulations!!! the equation that best represents the energy consumption of that residence is given by the line: f(x) = 2.37x+129.53; with it, you can estimate what your monthly consumption will be and every month the system will adjust this equation, getting closer and closer to the most likely reality :)

11#PyEx — Python — Parabolic Function: parabolic shape helps ensure that the bridge stays up and that the cables can sustain the weight of hundreds of cars and trucks each hour.

Fig 19. San Francisco Bridge — The Golden Gate Bridge is a suspension bridge spanning the Golden Gate, the one-mile-wide (1.6 km) strait connecting San Francisco Bay and the Pacific Ocean
Fig 20. the banana has a parabola-shaped curvature, in case you didn’t know...
Fig 21. Parabolas are also used in satellite dishes to help reflect signals that then go to a receiver. This specific satellite is the National Radio Astronomy Observatory, which operates the world premiere astronomical telescope operating from centimeter to millimeter wavelengths, and is located in Green Bank, West Virginia. Signals that go directly to the satellite will reflect off and back to the receiver after bouncing off the focus due to parabolas’ reflective properties.

The Problem: Obtain the parabola equation knowing that the points a (0,0), b (10,5), and c (20,0), in meters, belong to the structure of a bridge.

11_Solution (python cell code):from scipy.interpolate import *
x=[0,10,20]
y=[0,5,0]
f=lagrange(x,y)
print(f)
-0.05x²+x
Fig 22. The bridge parabolic function is: f(x) =-0.05x²+x; can it be easier than that?

12#PyEx — Python — Linear programming (LP): LP is a tool for solving optimization problems. In 1947, George Dantzig developed an efficient method, the simplex algorithm, for solving linear programming problems (also called LP). Since the development of the simplex algorithm, LP has been used to solve optimization problems in industries as diverse as banking, education, forestry, petroleum, and trucking. In a survey of Fortune 500 firms, 85% of the respondents said they had used linear programming, as a measure of the importance of linear programming in operations research:

Search for LP:

(Introduction to Linear Programming from ufrgs.br).

or

(http://www.optimization-online.org/DB_FILE/2011/09/3178.pdf)

The Problem: A Carrier Corporation has its deliveries optimized.

But on one day, one of his vehicles suffered an unusual attack:) was temporarily inoperative…

Fig 23. Track unusual attack :/

Now you need to formulate a Plan B for the delivery of two sets of important products A and B.

Each box of Product A weighs 20 kg and occupies 0.45m³.

Each box of Product B weighs 30 kg and occupies 0.35m³.

The profit for transporting Product A is $ 4.10.

The profit for transporting Product B is $ 5.40.

The truck has the capacity to transport 2 tons and the space of 30m³.

Knowing that the carrier wants to transport as many products as possible and obtain the highest possible profit, use linear programming, and solve the problem.

12_Solution (python cell code):import sys
!{sys.executable} -m pip install pulp
Fig 24. All the requirements are already satisfied \o/
from pulp import *
prob=LpProblem('Example', LpMaximize)
x1=LpVariable("Product A", 0)
x2=LpVariable("Product B", 0)
prob += 4.10*x1 + 5.40*x2
prob += 0.45*x1+0.35*x2 <= 30
prob += 20*x1+30*x2 <= 2000
prob.solve()
for v in prob.variables():
print(v.name,"=", v.varValue)
print("Max Profit = ", value(prob.objective))
Product_A = 30.769231
Product_B = 46.153846
Max Profit = 375.3846155
Fig 25. And there you have it! Congratulations!!! The result is Product_A = 30.769231 Product_B = 46.153846 Max Profit = 375.3846155, which means that to achieve maximum profit, the carrier will have to load its truck with 30 boxes of Product A, 46 boxes of Product B and the maximum profit of $ 375.38 will be reached!

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 the 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🏋!

Visualizing quaternions (4d numbers) with stereographic projection — from 3Blue1Brown

Introduction to Linear Programming from ufrgs.br (Universidade Federal do Rio Grande do Sul — Brazil)

PuLP: A Linear Programming Toolkit for Python by optimization-online.org

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! (this one:)

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!

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!