diff --git a/README.md b/README.md index f7cc03e..711f82a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Doing Math with Python -This repo contains the chapter programs and solutions to challenges discussed in "Doing Math with Python" - written by Amit Saha, published by No Starch Press. Please see the book [website](http://doingmathwithpython.github.io/) to learn more about the book, updates and reviews. +This repository basically contains the chapter programs and solutions to challenges discussed in "Doing Math with Python" - written by Amit Saha, published by No Starch Press. Please do check the [website](http://doingmathwithpython.github.io/) to learn more about the book, updates and reviews. # Chapter code @@ -12,12 +12,12 @@ This repo contains the chapter programs and solutions to challenges discussed in - [Chapter 6](https://github.com/doingmathwithpython/code/blob/master/chapter6/Chapter6.ipynb) - [Chapter 7](https://github.com/doingmathwithpython/code/blob/master/chapter7/Chapter7.ipynb) -If you know what Jupyter (previously, IPython notebooks are), click below to launch the program notebooks in Jupyter powered by Binder: +If you are familiar with Jupyter (previously, IPython notebooks are), click below to launch the program notebooks in Jupyter powered by Binder: [![Binder](http://mybinder.org/badge.svg)](http://mybinder.org/repo/doingmathwithpython/code) # Solutions to challenges -Please see the [blog post](https://doingmathwithpython.github.io/trying-out-solutions.html) on how to download these and try them out. +Please check the [blog post](https://doingmathwithpython.github.io/trying-out-solutions.html) on how to download these and try them out. diff --git a/explorations/PyScript/chap2/horizontal_bar_chart.html b/explorations/PyScript/chap2/horizontal_bar_chart.html new file mode 100644 index 0000000..60e0e77 --- /dev/null +++ b/explorations/PyScript/chap2/horizontal_bar_chart.html @@ -0,0 +1,46 @@ + + + + + + + - matplotlib + + + + +
+ + +import matplotlib.pyplot as plt +def create_bar_chart(data, labels): + # number of bars + num_bars = len(data) + # this list is the point on the y-axis where each + # bar is centered. Here it will be [1, 2, 3..] + positions = range(1, num_bars+1) + plt.barh(positions, data, align='center') + # set the label of each bar + plt.yticks(positions, labels) + plt.xlabel('Steps') + plt.ylabel('Day') + plt.title('Number of steps walked') + # Turns on the grid which may assist in visual estimation + plt.grid() + plt.show() + + +fig = plt.figure() +if __name__ == '__main__': + # Number of steps I walked during the past week + steps = [6534, 7000, 8900, 10786, 3467, 11045, 5095] + # Corresponding days + labels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] + create_bar_chart(steps, labels) +fig + + + + + + diff --git a/explorations/PyScript/chap2/newtons_gravitation.html b/explorations/PyScript/chap2/newtons_gravitation.html new file mode 100644 index 0000000..bff54c7 --- /dev/null +++ b/explorations/PyScript/chap2/newtons_gravitation.html @@ -0,0 +1,45 @@ + + + + + + + - matplotlib + + + + +
+ +import matplotlib.pyplot as plt +# draw the graph +def draw_graph(x, y): + plt.plot(x, y, marker='o') + plt.xlabel('Distance in meters') + plt.ylabel('Gravitational force in newtons') + plt.title('Gravitational force and distance') + plt.show() +def generate_F_r(): + # generate values for r + r = range(100, 1001, 50) + # empty list to store the calculated values of F + F = [] + # constant, G + G = 6.674*(10**-11) + # two masses + m1 = 0.5 + m2 = 1.5 + # calculate Force and add it to the list, F + for dist in r: + force = G*(m1*m2)/(dist**2) + F.append(force) + # call the draw_graph function + draw_graph(r, F) + +fig = plt.figure() +generate_F_r() +fig + + + + diff --git a/explorations/PyScript/chap2/nyc_forecast_owm.html b/explorations/PyScript/chap2/nyc_forecast_owm.html new file mode 100644 index 0000000..eae6c0d --- /dev/null +++ b/explorations/PyScript/chap2/nyc_forecast_owm.html @@ -0,0 +1,74 @@ + + + + + + + - matplotlib + - setuptools + - pyowm + - pytz + + + + +
+ +import pyodide +import json +import matplotlib.pyplot as plt +from unittest import mock +from datetime import datetime +import pytz + +from pyowm import OWM + +class MyResponse: + def __init__(self, status_code, message, json_body): + self.status_code = status_code + self.text = message + self.json_body = json_body + def json(self): + return self.json_body + +class JustEnoughRequests: + def __init__(self): + pass + + def get(self, uri, **kwargs): + print("Sending request to:", uri) + print("Got kwargs, igoring everyting other than params", kwargs) + query_params = [] + for k, v in kwargs["params"].items(): + query_params.append(k + "=" + v) + query_string = "&".join(query_params) + response = pyodide.open_url(uri + "?" + query_string) + json_response = response.getvalue() + d = json.loads(json_response) + return MyResponse(int(d["cod"]), d["message"], json.loads(json_response)) + +just_enough_requests = JustEnoughRequests() +fig = plt.figure() +with mock.patch('pyowm.commons.http_client.requests', just_enough_requests): + # Get a token from https://home.openweathermap.org/users/sign_up + owm = OWM('your token') + mgr = owm.weather_manager() + three_h_forecast = mgr.forecast_at_place('new york, us', '3h').forecast + temp = [] + date_time = [] + for w in three_h_forecast: + forecast_temp = w.temperature('celsius') + utc_dt = datetime.utcfromtimestamp(w.reference_time()).replace(tzinfo=pytz.utc) + tz = pytz.timezone('America/New_York') + dt = utc_dt.astimezone(tz) + date_time.append(dt.strftime('%Y-%m-%d %H:%M')) + temp.append(forecast_temp['temp']) + x = range(1, len(temp)+1) + plt.plot(x, temp, 'o-') + plt.xticks(x, date_time, rotation=45) +fig + + + + + diff --git a/explorations/PyScript/chap2/projectile_motion.html b/explorations/PyScript/chap2/projectile_motion.html new file mode 100644 index 0000000..7ad32d9 --- /dev/null +++ b/explorations/PyScript/chap2/projectile_motion.html @@ -0,0 +1,60 @@ + + + + + + + - matplotlib + + + + +
+ +from matplotlib import pyplot as plt +import math +def draw_graph(x, y): + print("Drawing the graph") + plt.plot(x, y) + plt.xlabel('x-coordinate') + plt.ylabel('y-coordinate') + plt.title('Projectile motion of a ball') + +def frange(start, final, interval): + numbers = [] + while start < final: + numbers.append(start) + start = start + interval + return numbers + +def draw_trajectory(u, theta): + theta = math.radians(theta) + g = 9.8 + # Time of flight + t_flight = 2*u*math.sin(theta)/g + # find time intervals + intervals = frange(0, t_flight, 0.001) + # list of x and y coordinates + x = [] + y = [] + for t in intervals: + x.append(u*math.cos(theta)*t) + y.append(u*math.sin(theta)*t - 0.5*g*t*t) + draw_graph(x, y) + +fig = plt.figure() +try: + u = float(input('Enter the initial velocity (m/s): ')) + theta = float(input('Enter the angle of projection (degrees): ')) +except ValueError: + print('You entered an invalid input') +else: + print(u,theta) + draw_trajectory(u, theta) +fig + + + + + + diff --git a/explorations/PyScript/chap2/projectile_motion_comparison.html b/explorations/PyScript/chap2/projectile_motion_comparison.html new file mode 100644 index 0000000..3fab935 --- /dev/null +++ b/explorations/PyScript/chap2/projectile_motion_comparison.html @@ -0,0 +1,57 @@ + + + + + + + - matplotlib + + + + +
+ +from matplotlib import pyplot as plt +import math +def draw_graph(x, y): + print("Drawing the graph") + plt.plot(x, y) + plt.xlabel('x-coordinate') + plt.ylabel('y-coordinate') + plt.title('Projectile motion of a ball') + +def frange(start, final, interval): + numbers = [] + while start < final: + numbers.append(start) + start = start + interval + return numbers + +def draw_trajectory(u, theta): + theta = math.radians(theta) + g = 9.8 + # Time of flight + t_flight = 2*u*math.sin(theta)/g + # find time intervals + intervals = frange(0, t_flight, 0.001) + # list of x and y coordinates + x = [] + y = [] + for t in intervals: + x.append(u*math.cos(theta)*t) + y.append(u*math.sin(theta)*t - 0.5*g*t*t) + draw_graph(x, y) + +fig = plt.figure() +u_list = [20, 40, 60] +theta = 45 +for u in u_list: + draw_trajectory(u, theta) + # Add a legend and show the graph + plt.legend(['20', '40', '60']) + plt.show() +fig + + + + diff --git a/explorations/PyScript/chap2/projectile_motion_comparison_gen.html b/explorations/PyScript/chap2/projectile_motion_comparison_gen.html new file mode 100644 index 0000000..24fa47e --- /dev/null +++ b/explorations/PyScript/chap2/projectile_motion_comparison_gen.html @@ -0,0 +1,88 @@ + + + + + + + - matplotlib + + + + +
+ +""" + +projectile_comparison_gen.py + +Compare the projectile motion of a body thrown with various combinations of initial +velocity and angle of projection. +""" + +import matplotlib.pyplot as plt +import math + +g = 9.8 + +def draw_graph(x, y): + plt.plot(x, y) + plt.xlabel('x-coordinate') + plt.ylabel('y-coordinate') + plt.title('Projectile motion at different initial velocities and angles') + +def frange(start, final, interval): + + numbers = [] + while start < final: + numbers.append(start) + start = start + interval + + return numbers + +def draw_trajectory(u, theta, t_flight): + # list of x and y co-ordinates + x = [] + y = [] + intervals = frange(0, t_flight, 0.001) + for t in intervals: + x.append(u*math.cos(theta)*t) + y.append(u*math.sin(theta)*t - 0.5*g*t*t) + + #create the graph + draw_graph(x, y) + +fig = plt.figure() +if __name__ == '__main__': + + num_trajectories = int(input('How many trajectories? ')) + + velocities = [] + angles = [] + for i in range(1, num_trajectories+1): + v = input('Enter the initial velocity for trajectory {0} (m/s): '.format(i)) + theta = input('Enter the angle of projection for trajectory {0} (degrees): '.format(i)) + velocities.append(float(v)) + angles.append(math.radians(float(theta))) + + for i in range(num_trajectories): + # calculate time of flight, maximum horizontal distance and + # maximum vertical distance + t_flight = 2*velocities[i]*math.sin(angles[i])/g + S_x = velocities[i]*math.cos(angles[i])*t_flight + S_y = velocities[i]*math.sin(angles[i])*(t_flight/2) - (1/2)*g*(t_flight/2)**2 + print('Initial velocity: {0} Angle of Projection: {1}'.format(velocities[i], math.degrees(angles[i]))) + print('T: {0} S_x: {1} S_y: {2}'.format(t_flight, S_x, S_y)) + print() + draw_trajectory(velocities[i], angles[i], t_flight) + + # Add a legend and show the graph + legends = [] + for i in range(0, num_trajectories): + legends.append('{0} - {1}'.format(velocities[i], math.degrees(angles[i]))) + plt.legend(legends) + plt.show() +fig + + + + diff --git a/explorations/PyScript/chap2/pylab_demo.html b/explorations/PyScript/chap2/pylab_demo.html new file mode 100644 index 0000000..891d16e --- /dev/null +++ b/explorations/PyScript/chap2/pylab_demo.html @@ -0,0 +1,30 @@ + + + + + + + - matplotlib + + + + +
+ +x_numbers = [1, 2, 3] +y_numbers = [2, 4, 6] +import matplotlib.pyplot as plt +fig = plt.figure() + +from pylab import plot, show +plot(x_numbers, y_numbers) +fig + +print("hello world!!") +#import matplotlib.pyplot as plt +#plt.plot(x_numbers, y_numbers) +#plt + + + + \ No newline at end of file diff --git a/explorations/PyScript/chap2/pyowm_pyodide.html b/explorations/PyScript/chap2/pyowm_pyodide.html new file mode 100644 index 0000000..5aa1cd2 --- /dev/null +++ b/explorations/PyScript/chap2/pyowm_pyodide.html @@ -0,0 +1,83 @@ + + + + + + + Pyodide test page
+ Open your browser console to see Pyodide output + + + diff --git a/explorations/PyScript/chap2/pyplot_demo_1.html b/explorations/PyScript/chap2/pyplot_demo_1.html new file mode 100644 index 0000000..6029b10 --- /dev/null +++ b/explorations/PyScript/chap2/pyplot_demo_1.html @@ -0,0 +1,27 @@ + + + + + + + - matplotlib + + + + +
+ +import matplotlib.pyplot + +def create_graph(): + x_numbers = [1, 2, 3] + y_numbers = [2, 4, 6] + matplotlib.pyplot.plot(x_numbers, y_numbers) + +fig = matplotlib.pyplot.figure() +create_graph() +fig + + + + diff --git a/explorations/PyScript/hello.html b/explorations/PyScript/hello.html new file mode 100644 index 0000000..83c309c --- /dev/null +++ b/explorations/PyScript/hello.html @@ -0,0 +1,20 @@ + + + + + + + - matplotlib + + + + +
+ +import matplotlib.pyplot as plt +plt.plot([1,2,3], [4,5,6]) +plt + + + +