├── .DS_Store ├── .gitattributes ├── .gitignore ├── Astronomy ├── Angle_stuff.ipynb ├── TopicsCensus.ipynb └── Week3_smallangle_doppler.ipynb ├── Intro To Python ├── __secret__ │ ├── solution14_socket_receive.py │ └── solution14_socket_send.py ├── semester1 │ ├── Week10_Challenge0.py │ ├── Week10_Challenge1.py │ ├── Week11_Snake.py │ ├── Week12_OnClasses.py │ ├── Week14_OpenChallenge.py │ ├── Week14_Solutions.py │ ├── Week15_receiver.py │ ├── Week15_server.py │ ├── Week6.py │ ├── Week8_Challenge0.py │ ├── Week8_Challenge1.py │ └── Week8_Challenge2.py ├── semester2 │ ├── checkkeyboard.py │ ├── mp3.py │ └── week8.py └── semester3 │ ├── Week1.ipynb │ ├── Week2.ipynb │ ├── Week3.ipynb │ ├── Week4.ipynb │ └── fakenews ├── LICENSE ├── Math Magic ├── Week10_Triggery.py ├── Week11_EXPONENTIALDERIVATIVE.py ├── Week14_Cowcooloose.py ├── Week14_Notebook_Cowcooloose.ipynb ├── Week15_Notebook.ipynb ├── Week16_FinalWeekWut.ipynb ├── Week8_PringlePlotter3000.py ├── Week9_QuiverPlotter.py ├── __other__ │ ├── Gravity.py │ ├── Week9_solutions.py │ ├── curve_fitting.py │ └── orbits.png └── untitled.txt ├── Math You Will Actually Use ├── Week10_StarTrek.py ├── Week11_Cowcooloose.py ├── Week11_EXPONENTIALDERIVATIVE.py ├── Week12_OrbitsimReprise.py ├── Week13_CarUncrashing.py ├── Week15_AI.py ├── Week2.py ├── Week3_GraphingCalculator.py ├── Week4_AllInOneGraphingCalculator.py ├── Week5_PringlePlotter3000.py ├── Week6_QuiverPlotter.py ├── Week6_Sympy.py ├── Week7.py ├── Week8_HowToTrig.py ├── Week9_1st_liveplotting.py ├── Week9_2nd_orbit_sim.py └── __secrets__ │ └── Week13_Solution.py ├── Python Projects ├── .DS_Store ├── ASSERT.py ├── AUDIOSIMULTANEOUS.py ├── AutoTyper.py ├── Cs5.wav ├── Filedownload.ipynb ├── Gs5.wav ├── HendricksTyper.py ├── PDB.py ├── QtGraphics.py ├── QtMagic.py ├── SAMSRADTHINGY.ipynb ├── Untitled.ipynb ├── Untitled1.ipynb └── moon.jpg ├── README.md ├── Spaceflight └── Tsiolkovsky.ipynb ├── Technology ├── W2_BinaryCodes.ipynb └── W3_CPU.ipynb └── __here__ /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonnyhyman/Programming-Classes/f56a9cf90e3b8e4aafad99644f1ed7e87ba14995/.DS_Store -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *.cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # Jupyter Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # SageMath parsed files 79 | *.sage.py 80 | 81 | # Environments 82 | .env 83 | .venv 84 | env/ 85 | venv/ 86 | ENV/ 87 | 88 | # Spyder project settings 89 | .spyderproject 90 | .spyproject 91 | 92 | # Rope project settings 93 | .ropeproject 94 | 95 | # mkdocs documentation 96 | /site 97 | 98 | # mypy 99 | .mypy_cache/ 100 | -------------------------------------------------------------------------------- /Astronomy/Angle_stuff.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import numpy as np" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 192, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "def arcstuff(deg):\n", 19 | " amin = np.modf(deg)[0] * 60\n", 20 | " asec = np.modf(amin)[0] * 60\n", 21 | " return amin, asec\n", 22 | "\n", 23 | "def angle(distance, baseline, deg=True):\n", 24 | " \n", 25 | " rad = np.arctan( (baseline/2) / distance ) * 2\n", 26 | " deg = np.rad2deg(rad)\n", 27 | " \n", 28 | " arcs = arcstuff(deg)\n", 29 | " \n", 30 | " return {'rad':rad, 'deg':deg, 'arcmin':round(arcs[0]), 'arcsec': round(arcs[1])}" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 193, 36 | "metadata": {}, 37 | "outputs": [ 38 | { 39 | "name": "stdout", 40 | "output_type": "stream", 41 | "text": [ 42 | "0.5323566883211995 0.5488888888888889\n" 43 | ] 44 | }, 45 | { 46 | "data": { 47 | "text/plain": [ 48 | "{'rad': 0.009291377006218175,\n", 49 | " 'deg': 0.5323566883211995,\n", 50 | " 'arcmin': 32.0,\n", 51 | " 'arcsec': 56.0}" 52 | ] 53 | }, 54 | "execution_count": 193, 55 | "metadata": {}, 56 | "output_type": "execute_result" 57 | } 58 | ], 59 | "source": [ 60 | "v = angle(1.496e8, 1.39e6)\n", 61 | "\n", 62 | "print(v['deg'], np.modf(v['deg'])[1] + v['arcmin']/60 + v['arcsec']/3600)\n", 63 | "v" 64 | ] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "metadata": {}, 69 | "source": [ 70 | " \n", 71 | "# $ d = \\frac{baseline}{2 * tan(\\frac{parallax}{2})} $\n" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 201, 77 | "metadata": {}, 78 | "outputs": [ 79 | { 80 | "data": { 81 | "text/plain": [ 82 | "2.6541124972341547e-06" 83 | ] 84 | }, 85 | "execution_count": 201, 86 | "metadata": {}, 87 | "output_type": "execute_result" 88 | } 89 | ], 90 | "source": [ 91 | "np.deg2rad(0 + 0 + 0.54745/3600)" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": 206, 97 | "metadata": {}, 98 | "outputs": [ 99 | { 100 | "data": { 101 | "text/plain": [ 102 | "1432394.4878270873" 103 | ] 104 | }, 105 | "execution_count": 206, 106 | "metadata": {}, 107 | "output_type": "execute_result" 108 | } 109 | ], 110 | "source": [ 111 | "2 / (4*np.tan(np.deg2rad(0.00001/2))) - 2 / (4*np.tan(np.deg2rad(0.00002/2)))" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [] 120 | } 121 | ], 122 | "metadata": { 123 | "kernelspec": { 124 | "display_name": "Python 3", 125 | "language": "python", 126 | "name": "python3" 127 | }, 128 | "language_info": { 129 | "codemirror_mode": { 130 | "name": "ipython", 131 | "version": 3 132 | }, 133 | "file_extension": ".py", 134 | "mimetype": "text/x-python", 135 | "name": "python", 136 | "nbconvert_exporter": "python", 137 | "pygments_lexer": "ipython3", 138 | "version": "3.6.5" 139 | } 140 | }, 141 | "nbformat": 4, 142 | "nbformat_minor": 2 143 | } 144 | -------------------------------------------------------------------------------- /Astronomy/TopicsCensus.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 5, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "PG_1 = {\n", 10 | " \"Quasars\": 5,\n", 11 | " \"Pulsars\":5,\n", 12 | " \"Star sytems\": 1,\n", 13 | " \"Black Holes\": 2,\n", 14 | " \"Gravitational Lensing\": 4,\n", 15 | " \"Space-time\" : 5,\n", 16 | " \"Inflation & Early-Cosmology\" : 8,\n", 17 | " \"Large Scale Universal Structural\" : 6,\n", 18 | " \"Exoplanets\" : 5,\n", 19 | " \"Galaxies\": 2,\n", 20 | " \"Galactic Evolution\": 10,\n", 21 | " \"Globular Clusters\": 4,\n", 22 | " \"Open Clusters\": 5,\n", 23 | " \"Superclusters\": 3,\n", 24 | " \"Galactic cluster\": 3,\n", 25 | " \"Nebulae\" : 6,\n", 26 | " \"Messier Objects\": 6,\n", 27 | " \"Exobiology\": 10,\n", 28 | " \"Stellar life-cycles\": 4,\n", 29 | " \"HS Diagrams\" : 8,\n", 30 | " \"Special relativity and the twin\" : 7.5,\n", 31 | " \"SETI\": 10,\n", 32 | "}" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 7, 38 | "metadata": {}, 39 | "outputs": [ 40 | { 41 | "data": { 42 | "text/plain": [ 43 | "{'Quasars': 5,\n", 44 | " 'Pulsars': 5,\n", 45 | " 'Star sytems': 1,\n", 46 | " 'Black Holes': 2,\n", 47 | " 'Gravitational Lensing': 4,\n", 48 | " 'Space-time': 5,\n", 49 | " 'Inflation & Early-Cosmology': 8,\n", 50 | " 'Large Scale Universal Structural': 6,\n", 51 | " 'Exoplanets': 5,\n", 52 | " 'Galaxies': 2,\n", 53 | " 'Galactic Evolution': 10,\n", 54 | " 'Globular Clusters': 4,\n", 55 | " 'Open Clusters': 5,\n", 56 | " 'Superclusters': 3,\n", 57 | " 'Galactic cluster': 3,\n", 58 | " 'Nebulae': 6,\n", 59 | " 'Messier Objects': 6,\n", 60 | " 'Exobiology': 10,\n", 61 | " 'Stellar life-cycles': 4,\n", 62 | " 'HS Diagrams': 8,\n", 63 | " 'Special relativity and the twin': 7.5,\n", 64 | " 'SETI': 10}" 65 | ] 66 | }, 67 | "execution_count": 7, 68 | "metadata": {}, 69 | "output_type": "execute_result" 70 | } 71 | ], 72 | "source": [ 73 | "PG_1" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": 57, 79 | "metadata": {}, 80 | "outputs": [], 81 | "source": [ 82 | "import numpy as np\n", 83 | "class adapt_dictionary:\n", 84 | " def __init__(self, other):\n", 85 | " self.internal = other\n", 86 | " \n", 87 | " def __getitem__(self, key):\n", 88 | " if key not in self.internal:\n", 89 | " self.internal[key] = 0\n", 90 | " return self.internal[key]\n", 91 | " \n", 92 | " def __setitem__(self, key, value):\n", 93 | " self.internal[key] = value\n", 94 | " \n", 95 | " def argsort(self):\n", 96 | " \n", 97 | " v = self.internal.values()\n", 98 | " i = np.argsort(list(v))\n", 99 | " \n", 100 | " return i" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": 58, 106 | "metadata": {}, 107 | "outputs": [], 108 | "source": [ 109 | "PG_2 = adapt_dictionary(PG_1)\n", 110 | "\n", 111 | "\n", 112 | "PG_2['astrometry'] += 1\n", 113 | "PG_2['star system formation'] += 1\n", 114 | "PG_2['annie jump canon'] += 1\n", 115 | "PG_2['stellar parallax'] += 1\n", 116 | "\n", 117 | "PG_2['stellar parallax'] += 1\n", 118 | "PG_2['star system formation'] += 1\n", 119 | "PG_2['entropy'] += 1\n", 120 | "PG_2['annie jump canon'] += 1\n", 121 | "PG_2['galileo galilei'] += 1\n", 122 | "\n", 123 | "PG_2['carl sagan'] += 1\n", 124 | "PG_2['annie jump canon'] += 1\n", 125 | "PG_2['vera rubin'] += 1\n", 126 | "\n", 127 | "PG_2['galaxy mergers'] += 1\n", 128 | "PG_2['optical astronomy'] += 1\n", 129 | "PG_2['stellar parallax'] += 1\n", 130 | "PG_2['astrometry'] += 1\n", 131 | "PG_2['star system formation'] += 1\n", 132 | "\n", 133 | "PG_2['cosmological heat death'] += 1\n", 134 | "PG_2['galaxy mergers'] += 1\n", 135 | "PG_2['astrometry'] += 1\n", 136 | "\n", 137 | "PG_2['galaxy mergers'] += 1\n", 138 | "PG_2['star system formation'] += 1\n", 139 | "PG_2['galaxy formation'] += 1\n", 140 | "PG_2['astrometry'] += 1\n", 141 | "PG_2['formation of the moon'] += 1\n", 142 | "\n", 143 | "PG_2['cosmological heat death'] += 1\n", 144 | "PG_2['infrared astronomy'] += 1\n", 145 | "PG_2['stellar parallax'] += 1\n", 146 | "\n", 147 | "PG_2['cosmological heat death'] += 1\n", 148 | "PG_2['star system formation'] += 1\n", 149 | "PG_2['edmond halley'] += 1\n", 150 | "\n", 151 | "PG_2['cosmological heat death'] += 1\n", 152 | "PG_2['star system formation'] += 1\n", 153 | "PG_2['galaxy formation'] += 1" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": 59, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "i = PG_2.argsort()" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": 62, 168 | "metadata": {}, 169 | "outputs": [ 170 | { 171 | "name": "stdout", 172 | "output_type": "stream", 173 | "text": [ 174 | " 10.00 ------> Galactic Evolution\n", 175 | " 10.00 ------> SETI\n", 176 | " 10.00 ------> Exobiology\n", 177 | " 8.00 ------> Inflation & Early-Cosmology\n", 178 | " 8.00 ------> HS Diagrams\n", 179 | " 7.50 ------> Special relativity and the twin\n", 180 | " 6.00 ------> Large Scale Universal Structural\n", 181 | " 6.00 ------> Nebulae\n", 182 | " 6.00 ------> Messier Objects\n", 183 | " 6.00 ------> star system formation\n", 184 | " 5.00 ------> Exoplanets\n", 185 | " 5.00 ------> Space-time\n", 186 | " 5.00 ------> Open Clusters\n", 187 | " 5.00 ------> Pulsars\n", 188 | " 5.00 ------> Quasars\n", 189 | " 4.00 ------> Globular Clusters\n", 190 | " 4.00 ------> Gravitational Lensing\n", 191 | " 4.00 ------> Stellar life-cycles\n", 192 | " 4.00 ------> cosmological heat death\n", 193 | " 4.00 ------> stellar parallax\n", 194 | " 4.00 ------> astrometry\n", 195 | " 3.00 ------> annie jump canon\n", 196 | " 3.00 ------> Galactic cluster\n", 197 | " 3.00 ------> Superclusters\n", 198 | " 3.00 ------> galaxy mergers\n", 199 | " 2.00 ------> Galaxies\n", 200 | " 2.00 ------> Black Holes\n", 201 | " 2.00 ------> galaxy formation\n", 202 | " 1.00 ------> formation of the moon\n", 203 | " 1.00 ------> Star sytems\n", 204 | " 1.00 ------> infrared astronomy\n", 205 | " 1.00 ------> optical astronomy\n", 206 | " 1.00 ------> vera rubin\n", 207 | " 1.00 ------> carl sagan\n", 208 | " 1.00 ------> galileo galilei\n", 209 | " 1.00 ------> entropy\n", 210 | " 1.00 ------> edmond halley\n" 211 | ] 212 | } 213 | ], 214 | "source": [ 215 | "k = list(PG_2.internal.keys())\n", 216 | "v = list(PG_2.internal.values())\n", 217 | "for ii in reversed(i):\n", 218 | " print(\"{:7.2f}\".format(v[ii]),' ------>', k[ii])" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": null, 224 | "metadata": {}, 225 | "outputs": [], 226 | "source": [] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": {}, 232 | "outputs": [], 233 | "source": [] 234 | } 235 | ], 236 | "metadata": { 237 | "kernelspec": { 238 | "display_name": "Python 3", 239 | "language": "python", 240 | "name": "python3" 241 | }, 242 | "language_info": { 243 | "codemirror_mode": { 244 | "name": "ipython", 245 | "version": 3 246 | }, 247 | "file_extension": ".py", 248 | "mimetype": "text/x-python", 249 | "name": "python", 250 | "nbconvert_exporter": "python", 251 | "pygments_lexer": "ipython3", 252 | "version": "3.6.5" 253 | } 254 | }, 255 | "nbformat": 4, 256 | "nbformat_minor": 2 257 | } 258 | -------------------------------------------------------------------------------- /Astronomy/Week3_smallangle_doppler.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | " \n", 8 | "# $ d = \\frac{baseline}{2 * tan(\\frac{parallax}{2})} $\n", 9 | "\n", 10 | "# $ tan(x) \\approx x $ \n", 11 | "\n", 12 | "# $ d \\approx \\frac{baseline}{parallax} $\n" 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": 38, 18 | "metadata": {}, 19 | "outputs": [], 20 | "source": [ 21 | "import numpy as np\n", 22 | "\n", 23 | "baseline = 10 # km\n", 24 | "parallax = np.deg2rad(140.0) # degrees" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 39, 30 | "metadata": {}, 31 | "outputs": [ 32 | { 33 | "data": { 34 | "text/plain": [ 35 | "1.8198511713310126" 36 | ] 37 | }, 38 | "execution_count": 39, 39 | "metadata": {}, 40 | "output_type": "execute_result" 41 | } 42 | ], 43 | "source": [ 44 | "d = baseline / (2 * np.tan(parallax/2))\n", 45 | "d" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": 40, 51 | "metadata": {}, 52 | "outputs": [ 53 | { 54 | "data": { 55 | "text/plain": [ 56 | "4.09255567950588" 57 | ] 58 | }, 59 | "execution_count": 40, 60 | "metadata": {}, 61 | "output_type": "execute_result" 62 | } 63 | ], 64 | "source": [ 65 | "d = baseline / parallax\n", 66 | "d" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "# How fast does redshift have to be to go infrared?" 76 | ] 77 | } 78 | ], 79 | "metadata": { 80 | "kernelspec": { 81 | "display_name": "Python 3", 82 | "language": "python", 83 | "name": "python3" 84 | }, 85 | "language_info": { 86 | "codemirror_mode": { 87 | "name": "ipython", 88 | "version": 3 89 | }, 90 | "file_extension": ".py", 91 | "mimetype": "text/x-python", 92 | "name": "python", 93 | "nbconvert_exporter": "python", 94 | "pygments_lexer": "ipython3", 95 | "version": "3.6.5" 96 | } 97 | }, 98 | "nbformat": 4, 99 | "nbformat_minor": 2 100 | } 101 | -------------------------------------------------------------------------------- /Intro To Python/__secret__/solution14_socket_receive.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from time import sleep 3 | 4 | UDP_IP = "127.0.0.1" # IP address to listen on 5 | UDP_PORT = 5005 # Port to listen on 6 | 7 | sock = socket.socket(socket.AF_INET, # Internet 8 | socket.SOCK_DGRAM) # UDP 9 | 10 | sock.bind((UDP_IP, UDP_PORT)) # start listening 11 | sock.settimeout(1) 12 | print('Listening!') 13 | 14 | while True: 15 | try: 16 | # Receive a total of 1024 bytes, then reset 17 | data, addr = sock.recvfrom(1024) 18 | data = data.decode('utf-8') # turn into a "normal string", not bytes 19 | print("Received message >>", data) 20 | 21 | except socket.timeout: 22 | # More than one second passed since we got a communication! 23 | print('...Still Listening...') 24 | -------------------------------------------------------------------------------- /Intro To Python/__secret__/solution14_socket_send.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | import socket 5 | 6 | UDP_IP = "127.0.0.1" # IP address 7 | UDP_PORT = 5005 # Port 8 | MESSAGE = "You've been hacked! This is yourself" # Message to send 9 | 10 | print("UDP target IP:", UDP_IP) 11 | print("UDP target port:", UDP_PORT) 12 | print("message:", MESSAGE) 13 | 14 | # Open an internet socket utilizing SOCK_DGRAM which means UDP 15 | 16 | while True: 17 | with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as conn: 18 | conn.sendto(bytes(MESSAGE,'utf-8'), (UDP_IP, UDP_PORT)) 19 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week10_Challenge0.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | This is a deep dive into FUNCTIONS 4 | 5 | 6 | What is a function? 7 | 8 | A function is a bunch of commands bundled into a group 9 | 10 | How do you write a function? 11 | 12 | Look below! 13 | 14 | CHALLENGES: (in order of HEAT = difficulty) 15 | 16 | Siberian Winter: Change the link of the Philly function 17 | 18 | Canada in Spring: Make the link an input to Philly, not a constant 19 | 20 | Spring in California: Convert Antonia's inputs to named inputs 21 | 22 | Summer in California: Write a new function which adds two numbers 23 | 24 | Rocket Engine: Convert these functions into a CLASS 25 | 26 | ''' 27 | 28 | import webbrowser 29 | 30 | def Franko(): 31 | print('Hello from Franko, the simple function') 32 | 33 | def Philly(): 34 | print('Hello from Philly, the funky phunction') 35 | print('You see, you can do a lot of stuff in one function') 36 | 37 | print('Like taking the square root of 1,245 to the power of pi!') 38 | 39 | import math 40 | 41 | sqrt1245_pi = math.sqrt(1245)**math.pi 42 | print('Which is exactly... ', sqrt1245_pi) 43 | 44 | print('You can even do fun stuff in here... Check this out...') 45 | webbrowser.open('http://www.jonnyhyman.com') 46 | 47 | def Antonia(argument1, argument2, TheyDontAllNeedToSayArgumentThough): 48 | print('Hello from Antonia, the fun function with fun inputs') 49 | print('These are my arguments:') 50 | print(argument1) 51 | print(argument2) 52 | print(TheyDontAllNeedToSayArgumentThough) 53 | 54 | webbrowser.open('https://media.giphy.com/media/R8n7YlPHe34dy/giphy.gif') 55 | 56 | def Kevin(named_argument = 'Wut', other_one = 'Hah', herp = 'derp' ): 57 | print('Hello from Kevin the function with NAMED inputs...') 58 | print('My inputs were...', named_argument, other_one, herp) 59 | 60 | 61 | #input(" ----> Notice how none of the functions run until you call them" 62 | # " //// [ENTER] to continue") 63 | 64 | print('_______________') # some space to be able to read easier 65 | 66 | Antonia() 67 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week10_Challenge1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A Hyper-Simple Graphical User Interface (GUI) using PyQt 3 | 4 | SETUP: 5 | 6 | To make a GUI, we need PyQt5 mod.... Just run in cmd: 7 | [pip install pyqt5] 8 | 9 | CHALLENGES: 10 | 11 | CHILLY : Change the window title 12 | CHILL : Change the y position of all the buttons USING A VARIABLE 13 | LUKEWARM : Change the window size 14 | WARM : Change what the buttons actually DO 15 | HOT : Add another button 16 | ROCKET : Add a program icon, change the font of the buttons text, 17 | & make window non-resizable by the user 18 | 19 | !!!!!!!!!!!!!!! THIS WILL NOT WORK ON CHROMEBOOKS !!!!!!!!!!!!!!!!!!!!!! 20 | ''' 21 | 22 | 23 | # The mod we use to create windows and stuff 24 | from PyQt5 import QtCore, QtGui, QtWidgets 25 | 26 | # the mod we use to tell the windows what OS they are running on 27 | import sys 28 | 29 | # used for opening webpages 30 | import webbrowser 31 | 32 | def open_link(link): 33 | webbrowser.open(link) 34 | 35 | def Success(): 36 | open_link('https://media.giphy.com/media/XreQmk7ETCak0/giphy.gif') 37 | 38 | def Motivate(): 39 | open_link('https://media.giphy.com/media/12XDYvMJNcmLgQ/giphy.gif') 40 | 41 | def oof(): 42 | open_link('https://giphy.com/gifs/jacksepticeye-a7JJdR8AYOOcw') 43 | 44 | def Boom(): 45 | open_link('https://media.giphy.com/media/xTiTnhFwjZHC8Ynrzi/giphy.gif') 46 | 47 | 48 | 49 | 50 | # the "class" GiphyButtons inherits from QMainWindow, which MAKES the window 51 | class GiphyButtons(QtWidgets.QMainWindow): 52 | 53 | def __init__(self, flexibleItems = False): 54 | 55 | # super is a special function which gives birth to the GiphyButtons class 56 | super(GiphyButtons, self).__init__() 57 | 58 | # how many pixels wide and tall the window should be 59 | self.resize(800, 600) # this function is from QMainWindow 60 | self.setWindowTitle("Giphy Buttons") # this function from QMainWindow 61 | 62 | # it is reccomended to make a "central" widget 63 | self.centralWidget = QtWidgets.QWidget(self) # master parent object 64 | self.setCentralWidget(self.centralWidget) # recommended in Qt5 65 | 66 | # this function (defined later, below) adds all the buttons 67 | # to the GUI 68 | self.setup_buttons() 69 | 70 | # this function actually CONNECTS all the buttons to do something 71 | self.connect_buttons() 72 | 73 | self.show() # show the window! 74 | 75 | def setup_buttons(self): 76 | ''' Add buttons to the gui ''' 77 | 78 | # QtWidgets is a submod with a bunch of stuff... Including buttons! 79 | self.success_button = QtWidgets.QPushButton("Success!", 80 | parent=self.centralWidget) 81 | 82 | self.success_button.move(10, 0) # move 10 pixels to the right, 0 down 83 | 84 | # lets keep track of where the right edge of each button is, 85 | # so that way we can lay them side by side, not on top of eachother 86 | right_edge_of_last_button = self.success_button.geometry().right() 87 | 88 | self.motivate_button = QtWidgets.QPushButton("Motivate!", 89 | parent=self.centralWidget) 90 | 91 | self.motivate_button.move(right_edge_of_last_button, 0) 92 | 93 | right_edge_of_last_button = self.motivate_button.geometry().right() 94 | 95 | self.boom_button = QtWidgets.QPushButton("EXPLODE!", 96 | parent=self.centralWidget) 97 | 98 | self.boom_button.move(right_edge_of_last_button, 0) 99 | 100 | right_edge_of_last_button = self.boom_button.geometry().right() 101 | 102 | self.oof_button = QtWidgets.QPushButton("OOF", 103 | parent=self.centralWidget) 104 | 105 | self.oof_button.move(right_edge_of_last_button, 0) 106 | 107 | right_edge_of_last_button = self.oof_button.geometry().right() 108 | 109 | 110 | 111 | def connect_buttons(self): 112 | ''' Connect gui buttons to do something ''' 113 | 114 | # Success function is defined before class 115 | self.success_button.clicked.connect(Success) 116 | 117 | # Success function is defined before class 118 | self.motivate_button.clicked.connect(Motivate) 119 | 120 | # Success function is defined before class 121 | self.boom_button.clicked.connect(Boom) 122 | 123 | self.oof_button.clicked.connect(oof) 124 | 125 | 126 | if __name__=='__main__': 127 | app = QtWidgets.QApplication(sys.argv) 128 | 129 | gui = GiphyButtons() 130 | gui.show() 131 | 132 | app.exec_() # complete all execution code in the GUI 133 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week11_Snake.py: -------------------------------------------------------------------------------- 1 | ''' 2 | PyGame: CHALLENGES 3 | 4 | 1. Make the game run really fast 5 | 2. Change the screen size 6 | 3. Change the background color 7 | 4. Make the WASD keys move the snake, instead of arrow keys 8 | 5. Change the shape of the apple objects 9 | 10 | ''' 11 | 12 | # Lots of imports here! 13 | import pygame 14 | import sys 15 | import time 16 | import random 17 | from pygame.locals import * 18 | 19 | # How many frames per second? Higher the number, faster the game 20 | FPS = 5 21 | 22 | # We are using a thing called pygame to do all the inputs and outputs 23 | pygame.init() # "init" is shorthand for "initialize" or start up / get ready 24 | 25 | fpsClock=pygame.time.Clock() # create a clock object to count time 26 | 27 | # define the screen size 28 | SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480 29 | 30 | # tell pygame what the screen should be like 31 | screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) 32 | 33 | # tell pygame we want a "surface" to draw pixels on 34 | surface = pygame.Surface(screen.get_size()) 35 | 36 | # who knows what this does...? 37 | surface = surface.convert() 38 | 39 | # fill the surface with white (255,255,255) in the red,green,blue scale 40 | surface.fill((255,255,255)) 41 | 42 | # create another clock for other reasons 43 | clock = pygame.time.Clock() 44 | 45 | # if you press a key, it will be repeated 40 times 46 | pygame.key.set_repeat(1, 40) 47 | 48 | # these variables IN ALL CAPS define IMPORTANT stuff for the game 49 | GRIDSIZE=10 # how big is each pixel? 50 | GRID_WIDTH = SCREEN_WIDTH / GRIDSIZE # how many horizontal grid squares? 51 | GRID_HEIGHT = SCREEN_HEIGHT / GRIDSIZE # how many vertical grid squares? 52 | UP = (0, -1) # which way is UP? (x,y) 53 | DOWN = (0, 1) # which way is DOWN? (x,y) 54 | LEFT = (-1, 0) # ... you get the idea 55 | RIGHT = (1, 0) 56 | 57 | # puts the "surface" into the window at the position (0,0) (top left corner) 58 | screen.blit(surface, (0,0)) 59 | 60 | def draw_box(surf, color, pos): 61 | r = pygame.Rect((pos[0], pos[1]), (GRIDSIZE, GRIDSIZE)) 62 | pygame.draw.rect(surf, color, r) 63 | 64 | def draw_circle(surf, color, pos): 65 | r = pygame.Rect((pos[0], pos[1]), (GRIDSIZE, GRIDSIZE)) 66 | pygame.draw.ellipse(surf, color, (pos[0],pos[1]), GRIDSIZE) 67 | 68 | class Snake(object): 69 | def __init__(self): 70 | self.lose() 71 | self.color = (0,0,0) 72 | 73 | def get_head_position(self): 74 | return self.positions[0] 75 | 76 | def lose(self): 77 | self.length = 1 78 | self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] 79 | self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) 80 | 81 | def point(self, pt): 82 | if self.length > 1 and (pt[0] * -1, pt[1] * -1) == self.direction: 83 | return 84 | else: 85 | self.direction = pt 86 | 87 | def move(self): 88 | cur = self.positions[0] 89 | x, y = self.direction 90 | new = (((cur[0]+(x*GRIDSIZE)) % SCREEN_WIDTH), (cur[1]+(y*GRIDSIZE)) % SCREEN_HEIGHT) 91 | if len(self.positions) > 2 and new in self.positions[2:]: 92 | self.lose() 93 | else: 94 | self.positions.insert(0, new) 95 | if len(self.positions) > self.length: 96 | self.positions.pop() 97 | 98 | def draw(self, surf): 99 | for p in self.positions: 100 | draw_box(surf, self.color, p) 101 | 102 | class Apple(object): 103 | def __init__(self): 104 | self.position = (0,0) 105 | self.color = (255,0,0) 106 | self.randomize() 107 | 108 | def randomize(self): 109 | self.position = (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, random.randint(0, GRID_HEIGHT-1) * GRIDSIZE) 110 | 111 | def draw(self, surf): 112 | draw_circle(surf, self.color, self.position) 113 | 114 | def check_eat(snake, apple): 115 | if snake.get_head_position() == apple.position: 116 | snake.length += 1 117 | apple.randomize() 118 | 119 | if __name__ == '__main__': 120 | snake = Snake() 121 | apple = Apple() 122 | while True: 123 | 124 | for event in pygame.event.get(): 125 | if event.type == QUIT: 126 | pygame.quit() 127 | sys.exit() 128 | elif event.type == KEYDOWN: 129 | if event.key == K_UP: 130 | snake.point(UP) 131 | elif event.key == K_DOWN: 132 | snake.point(DOWN) 133 | elif event.key == K_LEFT: 134 | snake.point(LEFT) 135 | elif event.key == K_RIGHT: 136 | snake.point(RIGHT) 137 | 138 | 139 | surface.fill((255,255,255)) 140 | snake.move() 141 | check_eat(snake, apple) 142 | snake.draw(surface) 143 | apple.draw(surface) 144 | font = pygame.font.Font(None, 36) 145 | text = font.render(str(snake.length), 1, (10, 10, 10)) 146 | textpos = text.get_rect() 147 | textpos.centerx = 20 148 | surface.blit(text, textpos) 149 | screen.blit(surface, (0,0)) 150 | 151 | pygame.display.flip() 152 | pygame.display.update() 153 | fpsClock.tick(FPS + snake.length/3) 154 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week12_OnClasses.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | """ 4 | ON: Classes / "Classifications" (but don't call them that) 5 | 6 | Classes are groups of similar things. For example, fruits... 7 | """ 8 | 9 | class Fruit: 10 | 11 | seeds = True 12 | sweet = True 13 | sour = None # not yet known (some fruits are, some fruits arent!) 14 | hard = None 15 | soft = None 16 | 17 | def __init__(self, sour = None, soft = None): 18 | # this runs when we run " apple = Fruit(...) " 19 | 20 | if soft: 21 | self.hard = False 22 | else: 23 | self.hard = True 24 | 25 | def eat(self): 26 | if self.hard: 27 | print('You are eating a hard apple') 28 | 29 | 30 | 31 | # Lets create.... An apple!! 32 | apple = Fruit(sour = True, soft = False) 33 | 34 | print('Apples have seeds:', apple.seeds) 35 | print('Apples are sour :', apple.sour) 36 | print('Apples are hard :', apple.hard) 37 | 38 | apple.sour = False # we can change internal things from the outside too! 39 | 40 | print('Apples are sour:', apple.sour) 41 | 42 | # -------- This is great and all, but there are so many kinds of fruit! 43 | # How could we possibly describe them all? 44 | # ... How about this: 45 | 46 | # Apples are a KIND of fruit! 47 | class Apple(Fruit): # (Fruit) here says that Apple INHERITS from Fruit! 48 | 49 | def __init__(self): 50 | 51 | # This SUPER command is magical... 52 | # It runs the __init__ function of the PARENT class (the inherited one) 53 | super().__init__(sour = True, hard = True) 54 | # Notice how that is a lot like calling Fruit(sour=True, hard=True) 55 | # .. That's because IT IS THE SAME THING WOAH 56 | 57 | def __str__(self): 58 | # This magical "dunder" function allows you to CUSTOM PRINT 59 | 60 | if self.hard: 61 | softness = 'hard' 62 | 63 | else: 64 | softness = 'soft' 65 | 66 | if self.sour: 67 | sourness = 'sour' 68 | else: 69 | sourness = 'not that sour' 70 | 71 | return "Apple which is " + softness + ' and ' + sourness 72 | 73 | """ -------------------------- CHALLENGE TIME! -------------------------- """ 74 | 75 | """ Write a vegetable class, or some other class of your choosing that is 76 | slightly more interesting than fruits and vegetables... :) """ 77 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week14_OpenChallenge.py: -------------------------------------------------------------------------------- 1 | """ 2 | THIS WEEK IS GOING TO BE DIFFERENT... 3 | 4 | The challenges are simpler than some we've done before, BUT: 5 | 6 | There is no code to begin with... DUN DUN DUN! 7 | 8 | --- These three things we will do together 9 | Challenge 1 : Create a class, representing OUR PYTHON CLASS 10 | which has methods/attributes to answer these questions: 11 | 12 | - How many people are in the class room? 13 | - How many people usually come to class? 14 | - What is the location of the class? 15 | - What are the names of all the students? 16 | - What is the name of the teacher? 17 | 18 | Challenge 2 : Use the module "urllib" to access https://www.khanacademy.org/ 19 | and then print the easter egg at the top of the html! 20 | 21 | Challenge 3 : Catch a failure and redirect with try/except 22 | 23 | For example, if you try to do: 24 | 1 + 'fish' ---> you'll get a "TypeError" 25 | 26 | So, use try/except to redirect that error into something else 27 | 28 | --- This one you guys are on your own (for a while) 29 | 30 | Challenge 4.1 : Use the "socket" module to send a message from one python 31 | window to another, on your computer screen 32 | 33 | Big hint: USE "UDP COMMUNICATION" AND GOOGLE 34 | 35 | Challenge 4.2 : 36 | (Teams) : Use the "socket" module to send a message to 37 | your friends computer (on the same wifi network) 38 | 39 | Big hint: USE "UDP COMMUNICATION" 40 | """ 41 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week14_Solutions.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | """ 4 | class Class: 5 | def __init__(self, number_of_people): 6 | 7 | self.location = 'Nuke town' 8 | self.gross_people = 10 9 | self.number_of_people = number_of_people 10 | 11 | Attendance = 100*(self.number_of_people / 12 | self.gross_people) 13 | 14 | Attendance = round(Attendance, 0) 15 | 16 | print('% Of Attendance = ', Attendance) 17 | print('At Location = ', self.location) 18 | 19 | def explode(self): 20 | self.number_of_people = 0 21 | print(self.location, 'exploded') 22 | print(self.number_of_people,'survivors remaining') 23 | 24 | our_class = Class(8) 25 | our_class.explode() 26 | """ 27 | 28 | 29 | 30 | try: 31 | import yoface 32 | 33 | except TypeError: 34 | print('TADA') 35 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week15_receiver.py: -------------------------------------------------------------------------------- 1 | """ 2 | 1. Send a message to yourself by running both server and receiver 3 | 2. Change the content of the message 4 | 3. Change the IP address of the message to target a friend's computer 5 | 4. Make it so that you can use the input() function to send a message 6 | 5. Make it so that this server can also receive, meaning your friend 7 | can send a message TO YOU 8 | 9 | """ 10 | 11 | import socket 12 | from time import sleep 13 | 14 | UDP_IP = "192.168.1.180" # IP address to listen on 15 | UDP_PORT = 5005 # Port to listen on 16 | 17 | sock = socket.socket(socket.AF_INET, # Internet 18 | socket.SOCK_DGRAM) # UDP 19 | 20 | sock.bind((UDP_IP, UDP_PORT)) # start listening 21 | sock.settimeout(1) 22 | print('Listening!') 23 | 24 | while True: 25 | try: 26 | # Receive a total of 1024 bytes, then reset 27 | data, addr = sock.recvfrom(1024) 28 | data = data.decode('utf-8') # turn into a "normal string", not bytes 29 | print("Received message >>", data) 30 | 31 | except socket.timeout: 32 | # More than one second passed since we got a communication! 33 | print('...Still Listening...') 34 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week15_server.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Challenges: 4 | 5 | 1. Send a message to yourself by running both server and receiver 6 | 2. Change the content of the message 7 | 3. Change the IP address of the message to target a friend's computer 8 | 4. Make it so that you can use the input() function to send a message 9 | 5. Make it so that this server can also receive, meaning your friend 10 | can send a message TO YOU 11 | 12 | """ 13 | import socket 14 | 15 | UDP_IP = "127.0.0.1" # IP address 16 | UDP_PORT = 5005 # Port 17 | MESSAGE = "You've been hacked! This is yourself" # Message to send 18 | 19 | print("UDP target IP:", UDP_IP) 20 | print("UDP target port:", UDP_PORT) 21 | print("message:", MESSAGE) 22 | 23 | # Open an internet socket utilizing SOCK_DGRAM which means UDP 24 | 25 | while True: 26 | MESSAGE = input() 27 | with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as conn: 28 | conn.sendto(bytes(MESSAGE,'utf-8'), (UDP_IP, UDP_PORT)) 29 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week6.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | print('projectors are purple') 4 | 5 | listOfOptions = ['Haii', 'Acers Suck', 6 | "I'm better than you", 7 | 8 | "The only time the word" 9 | " incorrectly isn't spelled " 10 | "incorrectly is when it's " 11 | "spelled correctly.", 12 | 13 | "I will be the last person to die in my" 14 | " lifetime"] 15 | 16 | 17 | print(random.choice(listOfOptions)) 18 | 19 | 20 | def function(inputs): 21 | print(inputs) 22 | return True 23 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week8_Challenge0.py: -------------------------------------------------------------------------------- 1 | ''' This is a reliable*** chatbot in a dense amount of code 2 | cd 3 | HELLOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO! 4 | 5 | YOUR CHALLENGES... 6 | 7 | IF YOU CHOOSE TO ACCEPT THEM: 8 | 9 | 10 | 1. Make 3 more scripted responses and test that they work 11 | 12 | 2. Make a special set of responses for when there is very 13 | little similarity. Things like "What?", "Uhh, riiiight..." 14 | 15 | HINTS: Make a new list, and use random.choice() on it 16 | if best_similarity < some smallish number (like 0.5) 17 | 18 | ''' 19 | 20 | responses = { 21 | 22 | # user typed : reponse string 23 | # LOWER CASE : ANY CASE 24 | 'your name' : 'My name is Python, duh! Yours?', 25 | 'how are you' : 'Great, how are you?', 26 | 'stupid' : 'Stupid is as stupid does.', 27 | 'smart' : 'Intelligence is in the eye of the beholder', 28 | 'weird' : 'Yeah.. Weird things are weird. You know?', 29 | 'i know' : "I thought so", 30 | 'stop' : "Why?", 31 | 'Haha' : "Haha I know right?", 32 | 33 | } 34 | 35 | # in case you forgot to type the keys (prompts) as all lower case 36 | 37 | for key in dict(responses): 38 | if key != key.lower(): # if some upper case characters 39 | 40 | # Add an extra entry with all lower case characters in prompt 41 | responses[key.lower()] = responses[key] 42 | 43 | 44 | '''-------------------------------- SIDE NOTE -------------------------------''' 45 | 46 | ''' *** In order to be reliable (allow typos), we can use "difflib" ! ''' 47 | 48 | 49 | import difflib 50 | 51 | a = 'jonny is a cool dude' # make a string 52 | b = 'j;nmy is a cewl dood' # make another, similar-ish 53 | 54 | # Calculate the percent similarity between them! 55 | similarity = difflib.SequenceMatcher(None, a, b).ratio() 56 | print(similarity) # will be 0.7 or 70 % similar 57 | 58 | '''-------------------------------- ANYWAY --------------------------------''' 59 | 60 | import random 61 | 62 | say_next = "Hi! How are you? >> " 63 | 64 | while True: # FOREVER (until we quit) 65 | 66 | text = input(say_next) 67 | text = text.lower() # make lowercase 68 | 69 | # Now go through the response dictionary and get the most similar input 70 | 71 | best_prompt = '' # I don't know yet, so make empty 72 | best_similarity = 0 # I don't know yet, so make 0 73 | 74 | for prompt, response in responses.items(): 75 | 76 | similarity = difflib.SequenceMatcher(None, text, prompt).ratio() 77 | 78 | if similarity > best_similarity: 79 | best_similarity = similarity 80 | best_prompt = prompt 81 | 82 | if best_similarity < 0.5: 83 | 84 | options = [ 85 | 'What in the world are you talking about? >> ', 86 | 'What? >>', 87 | 'Huh? >>', 88 | '????? >>', 89 | ] 90 | 91 | say_next = random.choice(options) 92 | 93 | else: 94 | say_next = responses[best_prompt] + ' >> ' # arrows to make clean print 95 | 96 | 97 | # Once we're done checking the entire responses list, SPEAK!! 98 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week8_Challenge1.py: -------------------------------------------------------------------------------- 1 | ''' This is a first name / last name dictionary & retrieval system 2 | 3 | Try this: 4 | 5 | 1. Add your name 6 | 2. Use the difflib tricks in Challenge0 to match SIMILAR names 7 | (instead of exact names) 8 | ''' 9 | 10 | 11 | database = { 12 | 'Luke':'Skywalker', 13 | 'Leia':'Skywalker', 14 | 'Han':'Solo', 15 | 'Chewie':'Chewbacca', 16 | 'Finn':'FN-2187', 17 | } 18 | 19 | # in case you forgot to type the keys (prompts) as all lower case 20 | 21 | for key in dict(database): 22 | if key != key.lower(): # if some upper case characters 23 | 24 | # Add an extra entry with all lower case characters in prompt 25 | database[key.lower()] = database[key] 26 | 27 | def sorry(): 28 | print('Sorry, no records found matching that name!') 29 | 30 | while True: 31 | 32 | typ = input('Search By First Name or Last Name? (type "first" or "last") >> ') 33 | 34 | if typ.lower() == 'first': 35 | 36 | name = input('First Name? >> ') 37 | name = name.lower() 38 | 39 | if name in database.keys(): 40 | print('Last Name Is', database[name]) 41 | else: 42 | sorry() 43 | 44 | elif typ.lower() == 'last': 45 | 46 | name = input('Last Name? >> ') 47 | name = name.lower() 48 | 49 | if name in database.values(): 50 | 51 | for first, last in database.items(): 52 | if last == name: 53 | print('First Name Is', first) 54 | break # quit this for loop 55 | else: 56 | sorry() 57 | -------------------------------------------------------------------------------- /Intro To Python/semester1/Week8_Challenge2.py: -------------------------------------------------------------------------------- 1 | ''' Launch a website on your web browser with python! 2 | 3 | REMEMBER 4 | 5 | ... With great power comes great responsibility... 6 | 7 | Challenges: 8 | 9 | 1. Make it go to a different website 10 | 2. Make it open as a new WINDOW, instead of new TAB 11 | 12 | ''' 13 | 14 | 15 | 16 | import webbrowser 17 | webbrowser.open('http://google.com', new=2) 18 | 19 | # SPOILER ALERT 20 | # new = 0? browser decides 21 | # new = 1? new window 22 | # new = 2? new tab 23 | 24 | # How do I know this? Go here and scroll down a bit and read 25 | '''https://docs.python.org/3.6/library/webbrowser.html''' 26 | -------------------------------------------------------------------------------- /Intro To Python/semester2/checkkeyboard.py: -------------------------------------------------------------------------------- 1 | from pynput import keyboard 2 | 3 | def on_press(key): 4 | try: 5 | print('alphanumeric key {0} pressed'.format(key.char)) 6 | except AttributeError: 7 | print('special key {0} pressed'.format(key)) 8 | 9 | def on_release(key): 10 | print('{0} released'.format(key)) 11 | if key == keyboard.Key.esc: 12 | # Stop listener 13 | return False 14 | 15 | # Collect events until released 16 | with keyboard.Listener( 17 | on_press=on_press, 18 | on_release=on_release) as listener: 19 | listener.join() 20 | -------------------------------------------------------------------------------- /Intro To Python/semester2/mp3.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | file = '2 Schizophrenia.mp3' 3 | 4 | pygame.init() 5 | pygame.mixer.init() 6 | pygame.mixer.music.load(file) 7 | pygame.mixer.music.play() 8 | 9 | 10 | 3 * self.width() / 4 11 | -------------------------------------------------------------------------------- /Intro To Python/semester2/week8.py: -------------------------------------------------------------------------------- 1 | """ 2 | SOME CORE CONCEPTS IN PYTHON worth going over 3 | 4 | - Lists, Tuples 5 | - Dictionaries 6 | - "Iterables" 7 | - Iterable manipulation tools: 8 | ''.join() 9 | += 's' or [] 10 | dictionary['key'] = blah 11 | .append, .extend 12 | 13 | - Writing functions from scratch: 14 | Arguments 15 | Keyword / Optional Arguments 16 | Return values 17 | Multiple return values 18 | Capturing ALL inputs 19 | Capturing ALL keyword inputss 20 | """ 21 | Ateam = ['this', 'list', 0, 1343.21341234,] 22 | Bteam = ('between','these','two') 23 | 24 | MerriamWebster = { 'lamp' : ['A lamp is a bright object that I love'], 25 | 'beef' : ["A beef is when you don't like someone"]} 26 | 27 | MerriamWebster['amp'] = 'Not a lamp' 28 | 29 | name = 'jonny' 30 | 31 | #for letter in name: 32 | # print(letter) 33 | 34 | for thing, otherthing in MerriamWebster.items(): 35 | print(thing, otherthing) 36 | 37 | """ 38 | ''.join() 39 | += 's' or [] 40 | dictionary['key'] = blah 41 | .append, .extend 42 | """ 43 | listofstring = [letter for letter in name] 44 | #print(listofstring) 45 | #print("".join(listofstring)) 46 | 47 | name += ' hyman' 48 | #name = name + ' hyman' 49 | 50 | 51 | imageformats = ['.png', '.jpg'] 52 | imageformats.append('.psd') 53 | imageformats.extend(['.jpeg','.pixar']) 54 | 55 | #print(imageformats + ['.tiff']) 56 | """" 57 | - Writing functions from scratch: 58 | Arguments 59 | Keyword / Optional Arguments 60 | Return values 61 | Multiple return values 62 | Capturing ALL inputs 63 | Capturing ALL keyword inputss 64 | """ 65 | #--------------------------------------- 66 | 67 | x, y = 0,0 68 | 69 | def direction(input_key, a, b, speed = 5): 70 | """ Update position by arrow key 71 | 72 | input: input_key(str) 73 | output: x,y (float) 74 | """ 75 | 76 | if input_key == 'w': 77 | b -= speed 78 | 79 | elif input_key == 's': 80 | b += speed 81 | 82 | elif input_key == 'd': 83 | a += speed 84 | 85 | elif input_key == 'a': 86 | a -= speed 87 | 88 | return a, b 89 | 90 | def function(*args, **kwargs): 91 | 92 | args[0] 93 | args[1] 94 | 95 | kwargs['IDONTKNOW'] 96 | 97 | print('ALL ARGS:', args) 98 | print('ALL KWARGS:', kwargs) 99 | 100 | print(direction('w', x, y, speed=100)) 101 | print(type(direction('w', x, y, speed=100))) 102 | 103 | function('a whole bunch', 'of random stuff', IDONTKNOW='Yeah, right?') 104 | 105 | #timer = Timer(timeout=1/60) 106 | #timer.connect(direction) 107 | -------------------------------------------------------------------------------- /Intro To Python/semester3/Week1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# TIME MACHINE\n", 8 | "\n", 9 | "![MARTY MCFLY](https://media.giphy.com/media/xsF1FSDbjguis/giphy.gif)" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 5, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "from time import time\n", 19 | "\n", 20 | "T = time()" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 6, 26 | "metadata": {}, 27 | "outputs": [ 28 | { 29 | "data": { 30 | "text/plain": [ 31 | "5.5073137283325195" 32 | ] 33 | }, 34 | "execution_count": 6, 35 | "metadata": {}, 36 | "output_type": "execute_result" 37 | } 38 | ], 39 | "source": [ 40 | "time() - T" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 7, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "from datetime import datetime" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 12, 55 | "metadata": {}, 56 | "outputs": [ 57 | { 58 | "data": { 59 | "text/plain": [ 60 | "datetime.datetime(2019, 1, 31, 23, 46, 28, 999586)" 61 | ] 62 | }, 63 | "execution_count": 12, 64 | "metadata": {}, 65 | "output_type": "execute_result" 66 | } 67 | ], 68 | "source": [ 69 | "datetime.utcnow()" 70 | ] 71 | }, 72 | { 73 | "cell_type": "markdown", 74 | "metadata": {}, 75 | "source": [ 76 | "# PATHLIB\n", 77 | "\n", 78 | "![WHERE AM I](https://media.giphy.com/media/2vlC9FMLSmqGs/giphy.gif)" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 14, 84 | "metadata": {}, 85 | "outputs": [], 86 | "source": [ 87 | "from pathlib import Path" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 17, 93 | "metadata": {}, 94 | "outputs": [ 95 | { 96 | "data": { 97 | "text/plain": [ 98 | "'/Users/jonny'" 99 | ] 100 | }, 101 | "execution_count": 17, 102 | "metadata": {}, 103 | "output_type": "execute_result" 104 | } 105 | ], 106 | "source": [ 107 | "str(Path(\"\").absolute())" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 19, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "fortnite = Path(\"universe\")" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": 22, 122 | "metadata": {}, 123 | "outputs": [ 124 | { 125 | "name": "stdout", 126 | "output_type": "stream", 127 | "text": [ 128 | "universe/ProjectSettings\n", 129 | "universe/Library\n", 130 | "universe/Packages\n", 131 | "universe/universe.sln\n", 132 | "universe/Assets\n" 133 | ] 134 | } 135 | ], 136 | "source": [ 137 | "for file in fortnite.iterdir():\n", 138 | " print(file)" 139 | ] 140 | }, 141 | { 142 | "cell_type": "markdown", 143 | "metadata": {}, 144 | "source": [ 145 | "# WRITING FILES with *PYTHON*\n", 146 | "![](https://media.giphy.com/media/mCRJDo24UvJMA/giphy.gif)" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": 25, 152 | "metadata": {}, 153 | "outputs": [], 154 | "source": [ 155 | "with open(\"folder.txt\", \"w\") as file:\n", 156 | " file.write(\"THIS IS A FILE YOOOOO\")" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 26, 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [ 165 | "link = \"https://media.giphy.com/media/mCRJDo24UvJMA/giphy.gif\"" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": 29, 171 | "metadata": {}, 172 | "outputs": [], 173 | "source": [ 174 | "import urllib.request\n", 175 | "\n", 176 | "response = urllib.request.urlopen(link)\n", 177 | "data = response.read() \n", 178 | "\n", 179 | "with open('dawgy.gif', 'wb') as file:\n", 180 | " file.write(data)" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "metadata": {}, 187 | "outputs": [], 188 | "source": [] 189 | } 190 | ], 191 | "metadata": { 192 | "kernelspec": { 193 | "display_name": "Python 3", 194 | "language": "python", 195 | "name": "python3" 196 | }, 197 | "language_info": { 198 | "codemirror_mode": { 199 | "name": "ipython", 200 | "version": 3 201 | }, 202 | "file_extension": ".py", 203 | "mimetype": "text/x-python", 204 | "name": "python", 205 | "nbconvert_exporter": "python", 206 | "pygments_lexer": "ipython3", 207 | "version": "3.6.5" 208 | } 209 | }, 210 | "nbformat": 4, 211 | "nbformat_minor": 2 212 | } 213 | -------------------------------------------------------------------------------- /Intro To Python/semester3/Week2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "# code cells" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "# Review" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 3, 22 | "metadata": {}, 23 | "outputs": [ 24 | { 25 | "name": "stdout", 26 | "output_type": "stream", 27 | "text": [ 28 | "I don't know\n" 29 | ] 30 | } 31 | ], 32 | "source": [ 33 | "# how do I print something? --> I don't know\n", 34 | "print(\"I don't know\")" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 4, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "# store the number one for later use\n", 44 | "# 1. Pick a name\n", 45 | "# 2. Assign\n", 46 | "coolvar = 1" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 10, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "# increase coolvar by one\n", 56 | "#coolvar = coolvar + 1\n", 57 | "coolvar += 1" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 9, 63 | "metadata": {}, 64 | "outputs": [ 65 | { 66 | "name": "stdout", 67 | "output_type": "stream", 68 | "text": [ 69 | "2\n" 70 | ] 71 | } 72 | ], 73 | "source": [ 74 | "print(coolvar)" 75 | ] 76 | }, 77 | { 78 | "cell_type": "markdown", 79 | "metadata": {}, 80 | "source": [ 81 | "# Measure time" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": 18, 87 | "metadata": {}, 88 | "outputs": [ 89 | { 90 | "name": "stdout", 91 | "output_type": "stream", 92 | "text": [ 93 | "1549579981.515384\n", 94 | "time.struct_time(tm_year=2019, tm_mon=2, tm_mday=7, tm_hour=22, tm_min=53, tm_sec=1, tm_wday=3, tm_yday=38, tm_isdst=0)\n" 95 | ] 96 | } 97 | ], 98 | "source": [ 99 | "# Get the CPU time\n", 100 | "import time\n", 101 | "print(time.time())\n", 102 | "print(str(time.gmtime()))" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "metadata": {}, 108 | "source": [ 109 | "# Measure datetime (UTC time)" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": 20, 115 | "metadata": {}, 116 | "outputs": [ 117 | { 118 | "name": "stdout", 119 | "output_type": "stream", 120 | "text": [ 121 | "2019-02-07 22:53:09.915135\n" 122 | ] 123 | } 124 | ], 125 | "source": [ 126 | "import datetime\n", 127 | "print(str(datetime.datetime.utcnow()))" 128 | ] 129 | }, 130 | { 131 | "cell_type": "markdown", 132 | "metadata": {}, 133 | "source": [ 134 | "# Directories and files and thingymadings" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": 80, 140 | "metadata": {}, 141 | "outputs": [ 142 | { 143 | "name": "stdout", 144 | "output_type": "stream", 145 | "text": [ 146 | "fake_directory\n", 147 | ".ipynb_checkpoints\n" 148 | ] 149 | } 150 | ], 151 | "source": [ 152 | "# print all of the files in the folder we are currently in on\n", 153 | "# the hard drive\n", 154 | "\n", 155 | "from pathlib import Path\n", 156 | "righthere = Path('.')\n", 157 | "\n", 158 | "for thing in righthere.iterdir():\n", 159 | " if thing.is_dir():\n", 160 | " print(thing)" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": 36, 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [ 169 | "var = [thing for thing in righthere.iterdir() if thing.is_dir()]" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": 38, 175 | "metadata": {}, 176 | "outputs": [ 177 | { 178 | "data": { 179 | "text/plain": [ 180 | "[PosixPath('fake_directory'), PosixPath('.ipynb_checkpoints')]" 181 | ] 182 | }, 183 | "execution_count": 38, 184 | "metadata": {}, 185 | "output_type": "execute_result" 186 | } 187 | ], 188 | "source": [ 189 | "var" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": null, 195 | "metadata": {}, 196 | "outputs": [], 197 | "source": [] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": null, 202 | "metadata": {}, 203 | "outputs": [], 204 | "source": [] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": null, 209 | "metadata": {}, 210 | "outputs": [], 211 | "source": [] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "execution_count": null, 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": null, 223 | "metadata": {}, 224 | "outputs": [], 225 | "source": [] 226 | }, 227 | { 228 | "cell_type": "markdown", 229 | "metadata": {}, 230 | "source": [ 231 | "![](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSbEc3q6zPvQ6bI58xd-5_xhgq44mT9ZqdLOmkofcejMA0aROFuM8snZDdD)" 232 | ] 233 | }, 234 | { 235 | "cell_type": "markdown", 236 | "metadata": {}, 237 | "source": [ 238 | "# FUNCTIONS" 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": 47, 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "def add( *args ):\n", 248 | " \n", 249 | " total = 0\n", 250 | " \n", 251 | " for thing in args:\n", 252 | " total += thing\n", 253 | " \n", 254 | " return total" 255 | ] 256 | }, 257 | { 258 | "cell_type": "code", 259 | "execution_count": 49, 260 | "metadata": {}, 261 | "outputs": [ 262 | { 263 | "data": { 264 | "text/plain": [ 265 | "1116" 266 | ] 267 | }, 268 | "execution_count": 49, 269 | "metadata": {}, 270 | "output_type": "execute_result" 271 | } 272 | ], 273 | "source": [ 274 | "result = add(var, 2, 3,10, 100, var2)\n", 275 | "result" 276 | ] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "execution_count": 64, 281 | "metadata": {}, 282 | "outputs": [ 283 | { 284 | "ename": "Exception", 285 | "evalue": "YA DUN GOOFED", 286 | "output_type": "error", 287 | "traceback": [ 288 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 289 | "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", 290 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m6\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0madd_lists\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 291 | "\u001b[0;32m\u001b[0m in \u001b[0;36madd_lists\u001b[0;34m(list1, list2)\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;31m# len of L1 not len of L2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlist1\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m!=\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlist2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0;32mraise\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"YA DUN GOOFED\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mlist3\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 292 | "\u001b[0;31mException\u001b[0m: YA DUN GOOFED" 293 | ] 294 | } 295 | ], 296 | "source": [ 297 | "# I WANT THIS:\n", 298 | "x = [1, 2, 3, 7]\n", 299 | "y = [4, 5, 6, 8]\n", 300 | "\n", 301 | "add_lists(x,y)" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": 81, 307 | "metadata": {}, 308 | "outputs": [], 309 | "source": [ 310 | "## HINT HINT\n", 311 | "def add_lists(list1, list2):\n", 312 | " \n", 313 | " # len of L1 not len of L2\n", 314 | " if len(list1) != len(list2):\n", 315 | " raise(Exception(\"YA DUN GOOFED\"))\n", 316 | " \n", 317 | " list3 = [0,] * len(list1)\n", 318 | " \n", 319 | " for i in range(len(list1)):\n", 320 | " list3[i] = list1[i] + list2[i]\n", 321 | " \n", 322 | " return list3" 323 | ] 324 | }, 325 | { 326 | "cell_type": "code", 327 | "execution_count": 84, 328 | "metadata": {}, 329 | "outputs": [ 330 | { 331 | "data": { 332 | "text/plain": [ 333 | "[0, 1, 2, 3, 4, 5, 6, 7]" 334 | ] 335 | }, 336 | "execution_count": 84, 337 | "metadata": {}, 338 | "output_type": "execute_result" 339 | } 340 | ], 341 | "source": [ 342 | "[n for n in range(0,8)]" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 85, 348 | "metadata": {}, 349 | "outputs": [ 350 | { 351 | "data": { 352 | "text/plain": [ 353 | "[101, 202, 303]" 354 | ] 355 | }, 356 | "execution_count": 85, 357 | "metadata": {}, 358 | "output_type": "execute_result" 359 | } 360 | ], 361 | "source": [ 362 | "add_lists([100,200,300], [1,2,3])" 363 | ] 364 | }, 365 | { 366 | "cell_type": "markdown", 367 | "metadata": {}, 368 | "source": [ 369 | "# NUMPY IS THE GREATEST OF ALL TIMES" 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": 69, 375 | "metadata": {}, 376 | "outputs": [], 377 | "source": [ 378 | "import numpy" 379 | ] 380 | }, 381 | { 382 | "cell_type": "code", 383 | "execution_count": 88, 384 | "metadata": {}, 385 | "outputs": [ 386 | { 387 | "data": { 388 | "text/plain": [ 389 | "array([ 100, 40000, 27000000])" 390 | ] 391 | }, 392 | "execution_count": 88, 393 | "metadata": {}, 394 | "output_type": "execute_result" 395 | } 396 | ], 397 | "source": [ 398 | "numpy.array([100, 200, 300]) ** numpy.array([1,2,3])" 399 | ] 400 | }, 401 | { 402 | "cell_type": "markdown", 403 | "metadata": {}, 404 | "source": [ 405 | "# Keyword (optional arguments)\n", 406 | "![](https://img.buzzfeed.com/buzzfeed-static/static/2015-03/3/15/enhanced/webdr07/anigif_enhanced-25359-1425414197-26.gif?downsize=700:*&output-format=auto&output-quality=auto)" 407 | ] 408 | }, 409 | { 410 | "cell_type": "code", 411 | "execution_count": 73, 412 | "metadata": {}, 413 | "outputs": [], 414 | "source": [ 415 | "def div(num, denom, fail_loudly = True):\n", 416 | " if denom == 0:\n", 417 | " if fail_loudly: # fail_loudly == True\n", 418 | " raise(Exception('BAD MATH'))\n", 419 | " else:\n", 420 | " print(\"YA DUN GOOFED, try again\")\n", 421 | " return\n", 422 | " \n", 423 | " return num / denom" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": 76, 429 | "metadata": {}, 430 | "outputs": [ 431 | { 432 | "data": { 433 | "text/plain": [ 434 | "3.0" 435 | ] 436 | }, 437 | "execution_count": 76, 438 | "metadata": {}, 439 | "output_type": "execute_result" 440 | } 441 | ], 442 | "source": [ 443 | "div(3, 1, fail_loudly = False)" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "execution_count": 77, 449 | "metadata": {}, 450 | "outputs": [ 451 | { 452 | "name": "stdout", 453 | "output_type": "stream", 454 | "text": [ 455 | "YA DUN GOOFED, try again\n" 456 | ] 457 | } 458 | ], 459 | "source": [ 460 | "div(3, 0, fail_loudly = False)" 461 | ] 462 | }, 463 | { 464 | "cell_type": "code", 465 | "execution_count": 78, 466 | "metadata": {}, 467 | "outputs": [ 468 | { 469 | "ename": "Exception", 470 | "evalue": "BAD MATH", 471 | "output_type": "error", 472 | "traceback": [ 473 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 474 | "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", 475 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdiv\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfail_loudly\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 476 | "\u001b[0;32m\u001b[0m in \u001b[0;36mdiv\u001b[0;34m(num, denom, fail_loudly)\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mdenom\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mfail_loudly\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;32mraise\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'BAD MATH'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"YA DUN GOOFED, try again\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 477 | "\u001b[0;31mException\u001b[0m: BAD MATH" 478 | ] 479 | } 480 | ], 481 | "source": [ 482 | "div(3, 0, fail_loudly = True)" 483 | ] 484 | }, 485 | { 486 | "cell_type": "code", 487 | "execution_count": null, 488 | "metadata": {}, 489 | "outputs": [], 490 | "source": [ 491 | "# arguments to a function : \"ARGS\"\n", 492 | "# keyword arguments to a f: \"KWARGS\"" 493 | ] 494 | } 495 | ], 496 | "metadata": { 497 | "kernelspec": { 498 | "display_name": "Python 3", 499 | "language": "python", 500 | "name": "python3" 501 | }, 502 | "language_info": { 503 | "codemirror_mode": { 504 | "name": "ipython", 505 | "version": 3 506 | }, 507 | "file_extension": ".py", 508 | "mimetype": "text/x-python", 509 | "name": "python", 510 | "nbconvert_exporter": "python", 511 | "pygments_lexer": "ipython3", 512 | "version": "3.6.5" 513 | } 514 | }, 515 | "nbformat": 4, 516 | "nbformat_minor": 2 517 | } 518 | -------------------------------------------------------------------------------- /Intro To Python/semester3/Week3.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "Get the CPU time now\n", 8 | "- Then later\n", 9 | "- Then the difference between the two" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "from time import time\n", 19 | "time()\n", 20 | "\n", 21 | "import time\n", 22 | "time.time()" 23 | ] 24 | }, 25 | { 26 | "cell_type": "markdown", 27 | "metadata": {}, 28 | "source": [ 29 | "#### Measure datetime (UTC time)" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 6, 35 | "metadata": {}, 36 | "outputs": [ 37 | { 38 | "name": "stdout", 39 | "output_type": "stream", 40 | "text": [ 41 | "2019-02-14 22:50:08.256085\n" 42 | ] 43 | } 44 | ], 45 | "source": [ 46 | "from datetime import datetime\n", 47 | "\n", 48 | "print(datetime.utcnow())" 49 | ] 50 | }, 51 | { 52 | "cell_type": "markdown", 53 | "metadata": {}, 54 | "source": [ 55 | "#### Make a function that adds two things and returns the sum" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "def add(a,b):\n", 65 | " return a+b" 66 | ] 67 | }, 68 | { 69 | "cell_type": "markdown", 70 | "metadata": {}, 71 | "source": [ 72 | "#### Make a function that adds any number of things and returns the sum" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": 35, 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "def add(*args):\n", 82 | " return sum(args)" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": 36, 88 | "metadata": {}, 89 | "outputs": [ 90 | { 91 | "data": { 92 | "text/plain": [ 93 | "698" 94 | ] 95 | }, 96 | "execution_count": 36, 97 | "metadata": {}, 98 | "output_type": "execute_result" 99 | } 100 | ], 101 | "source": [ 102 | "add(2,3)\n", 103 | "add(3,5,1,13,35,1,3,31,1,35,1,3,31,1,3,531)" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": 37, 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [ 112 | "def funk(*args):\n", 113 | " print(args, type(args))" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": 38, 119 | "metadata": {}, 120 | "outputs": [ 121 | { 122 | "name": "stdout", 123 | "output_type": "stream", 124 | "text": [ 125 | "(1, 2, 3) \n" 126 | ] 127 | } 128 | ], 129 | "source": [ 130 | "funk(1,2,3)" 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": 43, 136 | "metadata": {}, 137 | "outputs": [ 138 | { 139 | "name": "stdout", 140 | "output_type": "stream", 141 | "text": [ 142 | "(1, 35, 13, 1, 3, 31, 1, 3, 5, 1, 3, 1, 1) \n" 143 | ] 144 | } 145 | ], 146 | "source": [ 147 | "funk(1,35,13,1,3,31,1,3,5,1,3,1,1)" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": 8, 153 | "metadata": {}, 154 | "outputs": [ 155 | { 156 | "name": "stdout", 157 | "output_type": "stream", 158 | "text": [ 159 | "ZeroDivisionError('division by zero',) \n" 160 | ] 161 | } 162 | ], 163 | "source": [ 164 | "try:\n", 165 | " 1 / 0\n", 166 | " listy = [1,2,3,4,5, 55]\n", 167 | " listy[100]\n", 168 | " \n", 169 | "except IndexError:\n", 170 | " print('ya dun goofd')\n", 171 | "except NameError:\n", 172 | " print('watchyo name boi')\n", 173 | "except Exception as e:\n", 174 | " print((e.__repr__()), type(e))" 175 | ] 176 | }, 177 | { 178 | "cell_type": "markdown", 179 | "metadata": {}, 180 | "source": [ 181 | "# RANDOM CHOICES\n", 182 | "![](https://media.giphy.com/media/10CQOoOrvfpgbe/giphy.gif)" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": 3, 188 | "metadata": {}, 189 | "outputs": [ 190 | { 191 | "data": { 192 | "text/plain": [ 193 | "['a',\n", 194 | " 'b',\n", 195 | " 'c',\n", 196 | " 'd',\n", 197 | " 'e',\n", 198 | " 'f',\n", 199 | " 'g',\n", 200 | " 'h',\n", 201 | " 'i',\n", 202 | " 'j',\n", 203 | " 'k',\n", 204 | " 'l',\n", 205 | " 'm',\n", 206 | " 'n',\n", 207 | " 'o',\n", 208 | " 'p',\n", 209 | " 'q',\n", 210 | " 'r',\n", 211 | " 's',\n", 212 | " 't',\n", 213 | " 'u',\n", 214 | " 'v',\n", 215 | " 'w',\n", 216 | " 'x',\n", 217 | " 'y',\n", 218 | " 'z']" 219 | ] 220 | }, 221 | "execution_count": 3, 222 | "metadata": {}, 223 | "output_type": "execute_result" 224 | } 225 | ], 226 | "source": [ 227 | "abcs = list('abcdefghijklmnopqrstuvwxyz')\n", 228 | "abcs" 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": 4, 234 | "metadata": {}, 235 | "outputs": [], 236 | "source": [ 237 | "import random" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": 5, 243 | "metadata": {}, 244 | "outputs": [ 245 | { 246 | "name": "stdout", 247 | "output_type": "stream", 248 | "text": [ 249 | "['jeby', 'ajlgvuvm', 'ysixjc', 'dwtx', 'fxzw', 'yksf', 'rlgcj', 'jvx', 'wuwvvtoo', 'rutq', 'ohmei', 'omwyjh', 'ckkcyxjy', 'flatsvjp', 'orfxigvr', 'xvlio', 'dufhvy', 'vmnbdw', 'zqwcfvr', 'ioywdd', 'xapydif', 'muwgpgf', 'gtojl', 'ubissd', 'nadijg', 'jdnuh', 'gxv', 'qzwajqr', 'vnck', 'iem', 'qwonnuy', 'emt', 'sgen', 'qutfn', 'omvsiy', 'pavsnctz', 'wrvk', 'cnawry', 'jqatqu', 'gdobc', 'ecrzzg', 'tiiqhsbu', 'xdlir', 'pwmshybs', 'mbeq', 'mvc', 'scj', 'bohyzi', 'ijlfx', 'wwnuzcw', 'hewrpfwv', 'ovmlhh', 'rccx', 'ziybvd', 'lwdf', 'bppqec', 'dxama', 'avlt', 'efzyiuh', 'gsu', 'wett', 'tvu', 'ilmefmq', 'rrwa', 'rjaups', 'kfrsarks', 'nxbtiqr', 'dtst', 'mjjmsa', 'ffytsbcj', 'yjm', 'kef', 'zuun', 'hvr', 'qdtz', 'wobahqq', 'anmlr', 'xqgmsb', 'virxh', 'gaxfe', 'trxofr', 'nbn', 'xjf', 'bzqf', 'bspiyndj', 'mje', 'fwl', 'tpzvh', 'xjpqueml', 'bcbt', 'mgneh', 'iys', 'quyrkck', 'ondixy', 'hkqfe', 'ncqtwuyh', 'bep', 'bdrzuxzg', 'sdzyfn', 'qta', 'apgs', 'bxqth', 'hpkuluu', 'mdwxcpy', 'fukjdt', 'ncgkrl', 'kwkwcqt', 'qcedtdd', 'vrkkj', 'vvfmc', 'nsqn', 'viel', 'unm', 'kvsdp', 'obkrmh', 'qqyfsv', 'ste', 'czosg', 'wndj', 'sxlutfx', 'vhadpic', 'hwrspy', 'enpibhr', 'grkpds', 'wfd', 'ybzrxy', 'vhyswitj', 'dahhk', 'jio', 'tswfmuj', 'upebnbz', 'acuo', 'jaysvlu', 'mxeba', 'voly', 'tfpw', 'bdyt', 'cfdvsvt', 'vrc', 'gcvu', 'tnozrpq', 'gmnxrg', 'ria', 'rta', 'ewkbrkfi', 'soc', 'kxrmdxt', 'czo', 'sxotfkb', 'vsc', 'fmlchsvx', 'qkhxb', 'ibyr', 'ronvmuj', 'chcalugz', 'uyyqx', 'otqdcn', 'vmy', 'gzcf', 'zmz', 'uxo', 'crz', 'mjoydx', 'oykn', 'ntin', 'zhmj', 'yzrbq', 'udzjvsp', 'kjjrimnw', 'brvn', 'muqna', 'cesqxi', 'jpnwve', 'pfbrhu', 'fyktqftz', 'xuedzoym', 'ocfh', 'weswcics', 'ohaorst', 'ruyykg', 'rwt', 'mlwtkssv', 'qex', 'liumfhm', 'tujrmx', 'jwzmnw', 'urkf', 'hqyno', 'jsoqtwh', 'cpk', 'dksi', 'mdv', 'pbjtwtbe', 'knysv', 'yektjtjz', 'rshvbk', 'hkrc', 'cmzmcxzj', 'ojiqhre', 'pkmdic', 'moyzite', 'bec', 'wvd', 'ygjbmogn', 'dsmr', 'tdn', 'uizqc', 'klnostz', 'ifrnnv', 'eimxky', 'enbp', 'nzvqyxo', 'xnqp', 'gyf', 'apvrqr', 'omvp', 'ewpvmp', 'jqcpiv', 'zpqie', 'rdtsg', 'xkvqc', 'clgu', 'jjw', 'ufmzflus', 'bnudjf', 'qmufyhs', 'jmgad', 'wpvjyduf', 'vzar', 'bzli', 'tfe', 'nywmstld', 'gprtjr', 'tbxhi', 'gdayhxc', 'qvrcfg', 'jjeoajw', 'ayuf', 'imszqkl', 'jtyb', 'toujx', 'upl', 'dkuy', 'ekibwm', 'otsenv', 'cjlp', 'tjksy', 'uhlak', 'crnypso', 'ytplkobq', 'susnikcn', 'msaym', 'cgsr', 'unkte', 'fuki', 'nghzggia', 'hmlag', 'modrh', 'ufvdkx', 'caiaq', 'hukct', 'lyqilg', 'vklwhgkk', 'djra', 'bxwxokvd', 'pddz', 'hmccw', 'jgm', 'vdcf', 'vbu', 'luza', 'izlxinr', 'buyoyw', 'nlkvm', 'uqqgpnn', 'hxkph', 'yknr', 'leurav', 'uqcyq', 'gskft', 'uifroxrx', 'eyva', 'flkwfq', 'jqa', 'bieg', 'fit', 'vnnqsj', 'lrqe', 'ontocot', 'ifztdds', 'oyhlvgc', 'xhagncb', 'fkshojh', 'qklx', 'wyklfrn', 'hftclj', 'efjz', 'ybgw', 'ixlwsdxp', 'lyvedd', 'jnzk', 'jsivyn', 'yjyz', 'msjoo', 'vovymilc', 'dnf', 'eenpwtuk', 'gao', 'xyshnk', 'gogri', 'dea', 'rvatkfm', 'sudsj', 'oitht', 'ybpkqbgn', 'spsghpz', 'vlsvcm', 'prsrdg', 'vji', 'xxlntes', 'gpbupa', 'vznnr', 'dti', 'dgs', 'qrzwxdgz', 'hrp', 'ahiaoner', 'auvebgga', 'xoc', 'scsx', 'stqd', 'wuirtibf', 'rmsnxad', 'xeucsnat', 'lvce', 'onfx', 'zpktrw', 'nhgz', 'umkj', 'muwda', 'cwonrgdx', 'ljyadczk', 'cjw', 'adhbrz', 'nznr', 'qikkrgzq', 'mibq', 'yqzd', 'qremdsoi', 'wnvsz', 'sun', 'cetudxn', 'scap', 'divuixv', 'rsl', 'qapp', 'ueqf', 'xissperd', 'ewp', 'xppcnd', 'lfp', 'ccogomd', 'xjv', 'hsafzo', 'yfaoek', 'ibuy', 'bpmgu', 'hxgtkxag', 'brczds', 'ljew', 'iksqext', 'cggros', 'phzcuum', 'xak', 'llfb', 'kzml', 'xazs', 'yehmgakd', 'ztgpmjfm', 'rsuwfusw', 'cvriurv', 'swdx', 'tydzizd', 'gxbmvln', 'gszejj', 'vbxpg', 'uaxcq', 'vfygj', 'iaiimblp', 'ncah', 'ezgftqmo', 'covdu', 'dlznge', 'umsexza', 'mkso', 'rwnngorh', 'dugcw', 'aejlxqkt', 'ppkvpwwm', 'bvm', 'toklqk', 'bwteut', 'hmmaugnd', 'kctwjay', 'xmizw', 'tsvqv', 'mmpscs', 'gvx', 'aoyniifn', 'xumasus', 'tjnq', 'tbl', 'ryr', 'nteloh', 'izhs', 'dbct', 'dpzxbwv', 'uqch', 'uuv', 'llv', 'bheq', 'sdmvwk', 'xgggey', 'xkmkfv', 'erhszn', 'vivagiun', 'zxjsz', 'wstbgqtd', 'zjj', 'vvn', 'qbjqhs', 'tusqcig', 'zfkabp', 'aefi', 'imfmbiox', 'vivexjm', 'ppobnjis', 'vmec', 'nqqwtakh', 'inmyh', 'pgt', 'urxqb', 'qpbla', 'hyejlx', 'qxk', 'kuni', 'zjamlhr', 'wxaoe', 'jfwndibo', 'mbertjb', 'iaxcdaw', 'sfjiu', 'qnwud', 'xqynuf', 'pyhdkve', 'vfssslcu', 'wyqxbzm', 'cxjtbe', 'yenkdq', 'izzr', 'vpjcudda', 'nenretno', 'ctmb', 'xtiigf', 'vdybh', 'eggi', 'elpzqz', 'yrn', 'cvrwijra', 'ovm', 'yzctg', 'jnlxehs', 'zmwypng', 'cqurvrw', 'lyilv', 'vcfxetyz', 'ajr', 'bxactw', 'utgckt', 'bqfpiv', 'shnbu', 'ven', 'bcpfa', 'shnxs', 'wod', 'mzqvtnbo', 'pmwwzc', 'hkccdd', 'gjw', 'qecywif', 'karvu', 'eui', 'avuk', 'fgwxyvzq', 'tqwpg', 'vapxe', 'izquxl', 'kfq', 'dnzbb', 'abybbljt', 'iiyp', 'vyt', 'xvljn', 'ivijkt', 'xsutfc', 'pcn', 'rnqhqg', 'xobhno', 'iohbqpwk', 'fnviyhs', 'glc', 'yqqbib', 'aijeu', 'iknguzm', 'nxg', 'cytq', 'wxxs', 'ebbdh', 'rmrxuth', 'gulkey', 'mhy', 'oarpiyxv', 'ydiw', 'snz', 'zindbnd', 'aggqn', 'tbn', 'amxhmif', 'bmg', 'mnnjxj', 'uui', 'tkxpq', 'zuwaw', 'sdl', 'isn', 'genqthm', 'qrhczsjg', 'bnspl', 'wwrlsxd', 'rpxudf', 'sllv', 'hbjig', 'txo', 'sldssigs', 'byuok', 'mchhfg', 'bmwy', 'bqoh', 'ljcvg', 'gldyfwp', 'bzukbju', 'qma', 'yyjmf', 'mbiz', 'vjrf', 'efmmrzqs', 'ymext', 'hsgb', 'hbgpl', 'prd', 'oqbzwntv', 'kgrat', 'cdjqfxgj', 'cijbgfqy', 'zjbsffs', 'iwijuw', 'eplilpi', 'xfjwxpd', 'mxtc', 'bfecr', 'vojpli', 'ukyr', 'fwbllyqs', 'msh', 'vblyw', 'cjav', 'clagn', 'vst', 'tzszxsna', 'yxwnac', 'jcgza', 'lsdg', 'fuc', 'yaiyuzmi', 'apldny', 'kur', 'rdy', 'rslwtr', 'azgxkf', 'shlvxuux', 'zmi', 'akhhe', 'ocjoemjd', 'zeshe', 'avurxxkr', 'vvbpfou', 'dkdhqzy', 'avoxb', 'mfg', 'dvmuzgf', 'uto', 'qhykuetn', 'jzusutux', 'arnakmdg', 'noknq', 'qrm', 'jzltnvy', 'nclkqtx', 'vwn', 'ntxg', 'uygfea', 'qiudqak', 'golqrnp', 'rwukiyf', 'ofpvb', 'gubwgqj', 'ehgbzqe', 'dathjjmz', 'fxb', 'cgj', 'xxiifcez', 'xhk', 'ijp', 'trohzjv', 'sslin', 'fzlyfr', 'oircdp', 'teroauq', 'fzdxgu', 'syogbb', 'wehb', 'zjfx', 'lecszgz', 'jpf', 'pxy', 'mgfkbess', 'laho', 'syv', 'ajxgy', 'pzfujyla', 'xtxfkl', 'mjpidnu', 'tirhm', 'mqh', 'nemso', 'ymbfn', 'hdqtngmx', 'qfnbb', 'qxm', 'cxw', 'jsvqaao', 'mldw', 'kay', 'embp', 'czs', 'qklfz', 'lgaybes', 'jibecu', 'guwwdwum', 'ejjvm', 'ugrd', 'gxwe', 'dmhx', 'esynlg', 'qaurv', 'cmoj', 'bzz', 'fzdawn', 'jhfx', 'cvjwai', 'taxw', 'yevfg', 'uoocrzk', 'eqkhwfq', 'xykirmym', 'xtwhlnqg', 'decbssd', 'huycy', 'vlt', 'fqul', 'ceds', 'rouxl', 'mbj', 'ntz', 'gpxhzbc', 'yerwi', 'njh', 'ovy', 'clqc', 'aumi', 'ohsmbt', 'kymfiy', 'nsr', 'tzzdv', 'jvlhv', 'zizqy', 'iiukdsxw', 'pxpus', 'ejmhm', 'jrjkfibb', 'rewj', 'bezwuiww', 'poq', 'jbltxvc', 'uvzh', 'uxj', 'wzgnpu', 'qghqd', 'sszdrt', 'qirq', 'mejsr', 'kgfmgdz', 'rcaztql', 'lrvrgjyw', 'hanrfy', 'bwkuypp', 'cxlvtamh', 'kzpyya', 'yzo', 'fke', 'dvg', 'edkavxrs', 'sasuwhk', 'lutasgm', 'zaur', 'jpgp', 'fxz', 'uqkokbml', 'bua', 'fzgbfkhj', 'uttxbld', 'nns', 'xskcz', 'zobo', 'msy', 'brlmulf', 'thj', 'wmbf', 'nwzo', 'dttxhh', 'poj', 'cmuk', 'lajkxed', 'jwyxnmj', 'vwwyyh', 'npmoc', 'eaw', 'zgbhlpai', 'qvtkxk', 'uabwmrv', 'dqc', 'zhgec', 'wis', 'duovee', 'ohxxrpm', 'tfzhynam', 'xye', 'lqrumwe', 'aoumg', 'arnkozx', 'nvkxw', 'rhdu', 'kyml', 'uuwuvngj', 'sey', 'buhyxdlk', 'yhhpedef', 'enervi', 'mxhqpj', 'tqyk', 'kmuddi', 'uhew', 'jxkke', 'gfbllewy', 'ftwrfhv', 'ljtsx', 'aeizoxzj', 'pouimv', 'svtq', 'jah', 'vbplsm', 'jxjtmc', 'vnqq', 'dsjiu', 'rrvxdzpw', 'sgachwjy', 'wyicne', 'tpmndz', 'sqqwrud', 'yrpseixk', 'jpq', 'cypgc', 'btywck', 'jcqff', 'zsuugxxq', 'tcotlzr', 'ozz', 'xvy', 'bjt', 'kuhmkvpi', 'hubrixmr', 'ojcjn', 'jbmhqnh', 'bhw', 'zksbyk', 'kqdpy', 'abyru', 'fjjptq', 'gntd', 'ntbgome', 'jilbkd', 'vdfm', 'plbkol', 'drs', 'uarmznmn', 'xivvl', 'idse', 'dottuic', 'qlbfobln', 'sfvowtxe', 'xsskw', 'ngjvdz', 'aykubyv', 'ebihus', 'iilff', 'ylyebqub', 'uufsb', 'hhuc', 'aytfq', 'jnstxmtk', 'dzc', 'kijafsm', 'sbwrkrrf', 'ivariy', 'ighvnksx', 'citje', 'tdkablvy', 'fqmpoda', 'jqchjzva', 'pufxxakt', 'hbjehmtj', 'ghrg', 'dalkawl', 'ionkyudc', 'kypt', 'psgxmkz', 'qnsy', 'wdmijpvr', 'tesbsn', 'mnxai', 'uyuaqje', 'pidhwxt', 'axx', 'bnywuufh', 'jyqoxiq', 'humezkuc', 'syj', 'rpugxsu', 'ghivu', 'tnc', 'wifp', 'nxw', 'bqwfd', 'gsp', 'dhatlq', 'snjgwahs', 'daz', 'mtbrr', 'jrubp', 'ifa', 'bzmhfihn', 'zvubrpi', 'pie', 'tkli', 'lfxxtljt', 'lia', 'mxllxhr', 'syyjvfo', 'bkimx', 'syobi', 'uly', 'spcrkmd', 'xbbwrvkt', 'zqfsgan', 'ywsmjqzc', 'pdnlbggh', 'xkbjq', 'rbjjslz', 'sptvy', 'yjtwl', 'ibkhbrn', 'ylac', 'vfztibki', 'uzykuji', 'jzirf', 'hmapuek', 'lqnxljj', 'bzspqje', 'dtu', 'abhw', 'vvki', 'zhilq', 'tgqxvc', 'ckugvae', 'zue', 'xhairm', 'ydjeaos', 'mirmdnx', 'eoaulx', 'gtgl', 'pgrgh', 'xtmmrw', 'doxbrmhn', 'jje', 'rthog', 'hqndiowe', 'ymnvrgfa', 'rgnknxvw', 'ijld', 'wrxz', 'tcxcftia', 'arfw', 'eja', 'eupqj', 'vvlfdgd', 'iwgp', 'jjghlp', 'zfvuhukq', 'swtw', 'clkucspn', 'nmytutqu', 'djrly', 'tiurvbkk', 'sozmk', 'imnyl', 'sln', 'cakfxs', 'qeoi', 'rhvh', 'lar', 'ynbf', 'biqt', 'jcbnuyzv', 'zwb', 'vjtvccs', 'avad', 'rpcko', 'avwmmerr', 'wvqbbgo', 'spmdbozd', 'soww', 'qflxkzv', 'kkctqhm', 'pltkdxec', 'pppi', 'snbemg', 'lfousdmb', 'pfkcmhh', 'aukecm', 'gscv', 'geth', 'dexidpr', 'ufcuqthr', 'uuxarlw', 'poy', 'uxytvw', 'bkx', 'ajse', 'xep', 'mvazhgoc', 'zvmnbscr', 'uwajz', 'tdjgqqnu', 'abpfjb', 'vgqn', 'uhpnx', 'xwyv', 'qzudri', 'zfqez', 'llmxbqxh', 'uqxwe', 'wjvjbwyp', 'ttcrelik', 'kjq', 'gschtt', 'gvfdct', 'hmzostx', 'nzmgs', 'qcwxhc', 'pplpqg', 'kdrlgc', 'fbu', 'wtrfmq', 'xnh', 'ahkey', 'qfrfh', 'dlnvcq', 'hfpaxpw', 'zxf', 'ddrdwwar']\n" 250 | ] 251 | } 252 | ], 253 | "source": [ 254 | "check = []\n", 255 | "\n", 256 | "for _ in range(1000):\n", 257 | " \n", 258 | " word = ''\n", 259 | " \n", 260 | " for letter in range(random.randint(3,8)):\n", 261 | " word += random.choice(abcs)\n", 262 | " \n", 263 | " check.append(word)\n", 264 | "print(check)" 265 | ] 266 | }, 267 | { 268 | "cell_type": "code", 269 | "execution_count": 13, 270 | "metadata": {}, 271 | "outputs": [ 272 | { 273 | "name": "stdout", 274 | "output_type": "stream", 275 | "text": [ 276 | "abcdef\n" 277 | ] 278 | } 279 | ], 280 | "source": [ 281 | "print(\"abc\", end='')\n", 282 | "print('def')" 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": 14, 288 | "metadata": {}, 289 | "outputs": [], 290 | "source": [ 291 | "blah = []\n", 292 | "blah.append('abc')" 293 | ] 294 | }, 295 | { 296 | "cell_type": "code", 297 | "execution_count": 15, 298 | "metadata": {}, 299 | "outputs": [ 300 | { 301 | "data": { 302 | "text/plain": [ 303 | "['abc']" 304 | ] 305 | }, 306 | "execution_count": 15, 307 | "metadata": {}, 308 | "output_type": "execute_result" 309 | } 310 | ], 311 | "source": [ 312 | "blah" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": 16, 318 | "metadata": {}, 319 | "outputs": [], 320 | "source": [ 321 | "def check_dupes(listy):\n", 322 | " \n", 323 | " for h in listy:\n", 324 | " \n", 325 | " count = []\n", 326 | " \n", 327 | " # before for loop\n", 328 | " \n", 329 | " for i in listy:\n", 330 | " \n", 331 | " if h == i:\n", 332 | " count.append(i)\n", 333 | " \n", 334 | " if len(count) > 1:\n", 335 | " print(\"duplicate:\", count)" 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "execution_count": 17, 341 | "metadata": {}, 342 | "outputs": [], 343 | "source": [ 344 | "for h in check:\n", 345 | " if sum([h == i for i in check]) > 1:\n", 346 | " print(h, 'has a duplicate')" 347 | ] 348 | }, 349 | { 350 | "cell_type": "code", 351 | "execution_count": null, 352 | "metadata": {}, 353 | "outputs": [], 354 | "source": [ 355 | "#dupes = [[(h,i) for i in check] for h in check]\n", 356 | "#dupes" 357 | ] 358 | }, 359 | { 360 | "cell_type": "code", 361 | "execution_count": null, 362 | "metadata": {}, 363 | "outputs": [], 364 | "source": [ 365 | "check_dupes(check)" 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": 96, 371 | "metadata": {}, 372 | "outputs": [ 373 | { 374 | "data": { 375 | "text/plain": [ 376 | "True" 377 | ] 378 | }, 379 | "execution_count": 96, 380 | "metadata": {}, 381 | "output_type": "execute_result" 382 | } 383 | ], 384 | "source": [ 385 | "True == 1" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": 73, 391 | "metadata": {}, 392 | "outputs": [ 393 | { 394 | "name": "stdout", 395 | "output_type": "stream", 396 | "text": [ 397 | "1\n", 398 | "2\n", 399 | "3\n", 400 | "4\n", 401 | "5\n", 402 | "after 5\n" 403 | ] 404 | } 405 | ], 406 | "source": [ 407 | "for a in [1,2,3,4,5]:\n", 408 | " print(a)\n", 409 | "print('after', a)" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": 101, 415 | "metadata": {}, 416 | "outputs": [], 417 | "source": [ 418 | "xlist = []\n", 419 | "for i in [1,2,3,4,5]:\n", 420 | " xlist.append(h==i)" 421 | ] 422 | }, 423 | { 424 | "cell_type": "code", 425 | "execution_count": 102, 426 | "metadata": {}, 427 | "outputs": [], 428 | "source": [ 429 | "ylist = [(True) for i in [1,2,3,4,5] if h==i]" 430 | ] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": 5, 435 | "metadata": {}, 436 | "outputs": [ 437 | { 438 | "data": { 439 | "text/plain": [ 440 | "builtin_function_or_method" 441 | ] 442 | }, 443 | "execution_count": 5, 444 | "metadata": {}, 445 | "output_type": "execute_result" 446 | } 447 | ], 448 | "source": [ 449 | "import time\n", 450 | "type(time.time)" 451 | ] 452 | }, 453 | { 454 | "cell_type": "markdown", 455 | "metadata": {}, 456 | "source": [ 457 | "![WOW](https://media.giphy.com/media/xT0xeJpnrWC4XWblEk/giphy.gif)\n", 458 | "# END OF CLASS" 459 | ] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "execution_count": null, 464 | "metadata": {}, 465 | "outputs": [], 466 | "source": [] 467 | } 468 | ], 469 | "metadata": { 470 | "kernelspec": { 471 | "display_name": "Python 3", 472 | "language": "python", 473 | "name": "python3" 474 | }, 475 | "language_info": { 476 | "codemirror_mode": { 477 | "name": "ipython", 478 | "version": 3 479 | }, 480 | "file_extension": ".py", 481 | "mimetype": "text/x-python", 482 | "name": "python", 483 | "nbconvert_exporter": "python", 484 | "pygments_lexer": "ipython3", 485 | "version": "3.6.5" 486 | } 487 | }, 488 | "nbformat": 4, 489 | "nbformat_minor": 2 490 | } 491 | -------------------------------------------------------------------------------- /Intro To Python/semester3/Week4.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Challenge: Open a web page via python\n", 8 | "### *Specifically* : Create a function, which takes any link and opens that website" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 51, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "import webbrowser\n", 18 | "\n", 19 | "def twitter():\n", 20 | " \n", 21 | " user = input('http://twitter.com/')\n", 22 | " link = 'http://twitter.com/' + user\n", 23 | " webbrowser.open(link)" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 52, 29 | "metadata": {}, 30 | "outputs": [], 31 | "source": [ 32 | "twitter()" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 21, 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "goto('www.google.com')" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": 27, 47 | "metadata": {}, 48 | "outputs": [ 49 | { 50 | "data": { 51 | "text/plain": [ 52 | "True" 53 | ] 54 | }, 55 | "execution_count": 27, 56 | "metadata": {}, 57 | "output_type": "execute_result" 58 | } 59 | ], 60 | "source": [ 61 | "\"http://\" in \"http://www.google.com\") or (\"https://\" in \"http://www.google.com\")" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": 47, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "link = 'http://www'" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 48, 76 | "metadata": {}, 77 | "outputs": [ 78 | { 79 | "name": "stdout", 80 | "output_type": "stream", 81 | "text": [ 82 | "https://www\n" 83 | ] 84 | } 85 | ], 86 | "source": [ 87 | "if 'http://' in link:\n", 88 | " L = list(link) # turn link into a list list(\"adrian\") = ['a','d','r'...]\n", 89 | " L.insert(4,'s') # \n", 90 | " link = ''.join(L)\n", 91 | " print(link)" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "metadata": {}, 97 | "source": [ 98 | "#### Twitter users" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 50, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "user = input(\"Username:\") # hint hint" 108 | ] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "metadata": {}, 113 | "source": [ 114 | "# List Operations\n", 115 | "![](https://i.gifer.com/1RWC.gif)" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": 1, 121 | "metadata": {}, 122 | "outputs": [ 123 | { 124 | "data": { 125 | "text/plain": [ 126 | "range(0, 100)" 127 | ] 128 | }, 129 | "execution_count": 1, 130 | "metadata": {}, 131 | "output_type": "execute_result" 132 | } 133 | ], 134 | "source": [ 135 | "# Make a list of numbers between 1 and 100 (including and 1 and 100)\n", 136 | "\n", 137 | "# range(start, stop, step)\n", 138 | "range(90, 100)\n", 139 | "range(200, 9000, 100)\n", 140 | "range(100) # 0 -> 99" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": 9, 146 | "metadata": {}, 147 | "outputs": [], 148 | "source": [ 149 | "percents = [n for n in range(0,101)] # LIST COMPREHENSIONS\n", 150 | "\n", 151 | "ns = []\n", 152 | "for n in range(1,101): # THIS IS IDENTICAL\n", 153 | " ns.append(n)" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": 10, 159 | "metadata": {}, 160 | "outputs": [ 161 | { 162 | "data": { 163 | "text/plain": [ 164 | "[0,\n", 165 | " 1,\n", 166 | " 2,\n", 167 | " 3,\n", 168 | " 4,\n", 169 | " 5,\n", 170 | " 6,\n", 171 | " 7,\n", 172 | " 8,\n", 173 | " 9,\n", 174 | " 10,\n", 175 | " 11,\n", 176 | " 12,\n", 177 | " 13,\n", 178 | " 14,\n", 179 | " 15,\n", 180 | " 16,\n", 181 | " 17,\n", 182 | " 18,\n", 183 | " 19,\n", 184 | " 20,\n", 185 | " 21,\n", 186 | " 22,\n", 187 | " 23,\n", 188 | " 24,\n", 189 | " 25,\n", 190 | " 26,\n", 191 | " 27,\n", 192 | " 28,\n", 193 | " 29,\n", 194 | " 30,\n", 195 | " 31,\n", 196 | " 32,\n", 197 | " 33,\n", 198 | " 34,\n", 199 | " 35,\n", 200 | " 36,\n", 201 | " 37,\n", 202 | " 38,\n", 203 | " 39,\n", 204 | " 40,\n", 205 | " 41,\n", 206 | " 42,\n", 207 | " 43,\n", 208 | " 44,\n", 209 | " 45,\n", 210 | " 46,\n", 211 | " 47,\n", 212 | " 48,\n", 213 | " 49,\n", 214 | " 50,\n", 215 | " 51,\n", 216 | " 52,\n", 217 | " 53,\n", 218 | " 54,\n", 219 | " 55,\n", 220 | " 56,\n", 221 | " 57,\n", 222 | " 58,\n", 223 | " 59,\n", 224 | " 60,\n", 225 | " 61,\n", 226 | " 62,\n", 227 | " 63,\n", 228 | " 64,\n", 229 | " 65,\n", 230 | " 66,\n", 231 | " 67,\n", 232 | " 68,\n", 233 | " 69,\n", 234 | " 70,\n", 235 | " 71,\n", 236 | " 72,\n", 237 | " 73,\n", 238 | " 74,\n", 239 | " 75,\n", 240 | " 76,\n", 241 | " 77,\n", 242 | " 78,\n", 243 | " 79,\n", 244 | " 80,\n", 245 | " 81,\n", 246 | " 82,\n", 247 | " 83,\n", 248 | " 84,\n", 249 | " 85,\n", 250 | " 86,\n", 251 | " 87,\n", 252 | " 88,\n", 253 | " 89,\n", 254 | " 90,\n", 255 | " 91,\n", 256 | " 92,\n", 257 | " 93,\n", 258 | " 94,\n", 259 | " 95,\n", 260 | " 96,\n", 261 | " 97,\n", 262 | " 98,\n", 263 | " 99,\n", 264 | " 100]" 265 | ] 266 | }, 267 | "execution_count": 10, 268 | "metadata": {}, 269 | "output_type": "execute_result" 270 | } 271 | ], 272 | "source": [ 273 | "[m*0.01 for m in percents]" 274 | ] 275 | }, 276 | { 277 | "cell_type": "code", 278 | "execution_count": 17, 279 | "metadata": {}, 280 | "outputs": [ 281 | { 282 | "data": { 283 | "text/plain": [ 284 | "0.6900000000000001" 285 | ] 286 | }, 287 | "execution_count": 17, 288 | "metadata": {}, 289 | "output_type": "execute_result" 290 | } 291 | ], 292 | "source": [ 293 | "round(69 * 0.01, 2)" 294 | ] 295 | }, 296 | { 297 | "cell_type": "markdown", 298 | "metadata": {}, 299 | "source": [ 300 | "#### [(this is where stuff happens) for (get from list) in list]" 301 | ] 302 | }, 303 | { 304 | "cell_type": "code", 305 | "execution_count": null, 306 | "metadata": {}, 307 | "outputs": [], 308 | "source": [] 309 | } 310 | ], 311 | "metadata": { 312 | "kernelspec": { 313 | "display_name": "Python 3", 314 | "language": "python", 315 | "name": "python3" 316 | }, 317 | "language_info": { 318 | "codemirror_mode": { 319 | "name": "ipython", 320 | "version": 3 321 | }, 322 | "file_extension": ".py", 323 | "mimetype": "text/x-python", 324 | "name": "python", 325 | "nbconvert_exporter": "python", 326 | "pygments_lexer": "ipython3", 327 | "version": "3.6.5" 328 | } 329 | }, 330 | "nbformat": 4, 331 | "nbformat_minor": 2 332 | } 333 | -------------------------------------------------------------------------------- /Intro To Python/semester3/fakenews: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 2 6 | } 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 jonnyhyman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Math Magic/Week10_Triggery.py: -------------------------------------------------------------------------------- 1 | import numpy as np # the first thing any starfleet officer does...! 2 | ''' 3 | Part 1: Romulans.........................! 4 | ''' 5 | x = 1000 # km 6 | y = 500 # km 7 | 8 | # since we can may treat the x and y as sides of a triangle, 9 | # we can use the pythagorean theorem to get the hypotenuse (range)! 10 | 11 | # range**2 = x**2 + y**2 12 | # range = + sqrt(x**2 + y**2) ORR!! - sqrt(x**2 + y**2) 13 | # although, the ship probably isn't behind us so ignore the negative sqrt... 14 | 15 | range = np.sqrt( np.power(x,2) + np.power(y,2) ) # power == ** ... KAPOW! 16 | mark = np.arctan(y / x) # reverse sin (y/x) 17 | mark = np.rad2deg(mark) 18 | 19 | print('Captain, the Romulan ship is', range,'kilometers, mark',mark,' and closing...') 20 | 21 | 22 | input('ENTER to continue') 23 | 24 | ''' 25 | Part 2: THE BORG AAAAHHHH! 26 | ''' 27 | 28 | mark0 = 65 # degrees 29 | mark1 = 55 # degrees 30 | diameter = 3 # kilometers 31 | 32 | # step 0: assume the borg ship is coming at you face-on 33 | # (no angling from your viewpoint)... Makes two triangle angles the same 34 | 35 | # step 1: split the (not-90-degree) triangle into two halves, so that 36 | # in the middle are two 90 degree triangles 37 | 38 | # step 2: figure out (mark0 - mark1)/2, the triangle's inner angle 39 | 40 | inner = (mark0 - mark1) / 2 41 | 42 | # step 3: sin = opp / hyp, in our case sin(inner) = (3km/2) / range 43 | # step 4: solve for range --> range = (diameter/2) / np.sin(np.deg2rad(inner)) 44 | # ......... you could use sympy in step 4 but I cheated and used paper ........ 45 | 46 | range = (diameter/2) / np.sin(np.deg2rad(inner)) 47 | 48 | print('Captain, the Borg ship is', range, 'kilometers and closing...') 49 | 50 | import webbrowser # shhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh 51 | webbrowser.open('https://media.giphy.com/media/tK3THRanG0d0c/giphy.gif') 52 | -------------------------------------------------------------------------------- /Math Magic/Week11_EXPONENTIALDERIVATIVE.py: -------------------------------------------------------------------------------- 1 | import sympy 2 | 3 | x = sympy.Symbol('x') 4 | 5 | expression = sympy.exp(x) 6 | 7 | print() 8 | print() 9 | print(expression) 10 | 11 | derivative = sympy.diff(expression, x) 12 | 13 | print('derivative:', derivative) 14 | -------------------------------------------------------------------------------- /Math Magic/Week14_Cowcooloose.py: -------------------------------------------------------------------------------- 1 | 2 | print( 3 | ''' 4 | 5 | Welcome to Cowcooloose, 6 | Here we will learn how cows are cool and often loosely correlated to math. 7 | 8 | /; ;\\ 9 | __ \\____// 10 | /{_\\_/ `'\____ 11 | \\___ ---(=)--(=)--} 12 | _____________________________/ :--' 13 | ,-,'`@@@@@@@@ @@@@@@ \\_ `__\\ 14 | ;:( @@@@@@@@@ @@@ \\___(o'o) 15 | :: ) @@@@ @@@@@@ ,'@@( `====' 16 | :: : @@@@@: @@@@ `@@@: 17 | :: \\ @@@@@: @@@@@@@) ( '@@@' 18 | ;; /\\ /`, @@@@@@@@@\\ :@@@@@) 19 | ::/ ) {_----------------: :~`,~~; 20 | ;;'`; : ) : / `; ; 21 | ;;;; : : ; : ; ; : 22 | `'`' / : : : : : : 23 | )_ \\__; ";" :_ ; \\_\\ `,',' 24 | :__\\ \\ * `,'* \\ \\ : \\ * 8`;'* * 25 | `^' \\ :/ `^' `-^-' \\v/ : \\/ -Bill Ames- 26 | 27 | 28 | ''' 29 | ) 30 | 31 | print( 32 | ''' 33 | A cow walks 3.2 miles in 1.5 hours, hungry for the patch of grass ahead 34 | What is the speed of the cow in "mi/h"? 35 | 36 | Cows like imperial units btw... Weirdos... 37 | ''') 38 | 39 | ''' since dist = 3.2, and time = 1.5, and speed = distance / time, 40 | ''' 41 | 42 | ''' we'll use this later, don't mind it for now ''' 43 | def pause_continue(): 44 | print() 45 | input(' ... [ENTER] to continue') 46 | print('________________________') 47 | print() 48 | 49 | dist = 3.2 50 | time = 1.5 51 | 52 | speed = dist / time 53 | 54 | pause_continue() 55 | 56 | print('The cow walks at', speed, 'mi per hour') 57 | 58 | pause_continue() 59 | 60 | 61 | print(''' 62 | Now, what if as the cow walked, she *accelerated* (she's in a rush you see). 63 | If she sped up 1.2 mi per hour per hour, how fast is she going in 2 hrs? 64 | ''') 65 | 66 | accel = 1.2 # mi/hr per hr 67 | time = 2.0 68 | 69 | speed = speed + accel * time # mi/hr + (mi/hr)/hr * hr 70 | 71 | pause_continue() 72 | 73 | print('The cow walks at', speed, 'mi per hour after', time, 'hours') 74 | 75 | pause_continue() 76 | 77 | 78 | print(''' 79 | Now, more realistically, the cow will oscillate in speed... 80 | 81 | Let's use sine (y=sin(x)) to model how she changes speed... 82 | 83 | so, let's try speed = 2 * sin(time / 2) + 2 84 | 85 | IMPORTANT: Change of units for time, let time be in MINUTES 86 | 87 | ... What does that look like on a graph? 88 | ''') 89 | 90 | pause_continue() 91 | 92 | import sympy 93 | import numpy as np 94 | import matplotlib.pyplot as plt 95 | 96 | time = sympy.symbols('time') 97 | speed = 2 * sympy.sin(time / 2) + 2 98 | 99 | # lamdify() is a great function. 100 | # It turns sympy "symbolic" functions into real ones that can be USED! 101 | speed_numpy = sympy.lambdify( time, # speed(time) 102 | speed, # speed function (symbolic) 103 | modules=['numpy'] # use numpy's functions to make it real 104 | ) 105 | 106 | time_walking = 60.0 # spend 60 minutes walking 107 | times = np.linspace(0, time_walking, 200) # make 100 points between 0 and 60 min 108 | speeds = speed_numpy(times) # make 100 speeds at each time in times 109 | 110 | plt.plot(times, speeds) 111 | plt.xlabel("Time [minutes]") 112 | plt.ylabel("Cow Speed [mi/h]") 113 | plt.show() 114 | 115 | pause_continue() 116 | 117 | print(''' 118 | A trickier one now... How FAR does she walk in 60 minutes at this 119 | alternating speed? 120 | 121 | This is impossible to get perfect without calculus btw... 122 | ''') 123 | 124 | pause_continue() 125 | 126 | print(''' 127 | To do this, basically we do this: 128 | 129 | Figure out the Integral of Speed between time = 0 and time = 60 130 | 131 | What does that mean? 132 | 133 | In a nutshell it means to do this: 134 | 135 | for a ton of tiny slices of time (like really small, seriously): 136 | get the speed value at the start of that time slice 137 | 138 | take the speed * the width of the time slice 139 | (essentially get the area of the rectangle... 140 | (see whiteboard explanation for details)) 141 | 142 | add that speed*timewidth to a running total of areas 143 | 144 | at the end of it all, the total area gathered will be the 145 | amount of distance covered in that time... 146 | 147 | Isn't that kind of crazy? 148 | 149 | ------------------------- 150 | 151 | None of that actually matters, in practice, though. 152 | 153 | All you have to do is this: [see code] 154 | ''') 155 | 156 | # Remember, we already defined speed and time up above when we plotted 157 | 158 | distance = sympy.integrate(speed, (time, 0, time_walking) ) 159 | 160 | # evaluate result into a float (decimal number) 161 | distance_walked = distance.evalf() 162 | 163 | pause_continue() 164 | print('The cow walks a grand total of', distance_walked, 'miles in', 165 | time_walking, 'minutes') 166 | 167 | print("That's a fast cow!") 168 | print("The cow's distance function is:", sympy.integrate(speed, time)) 169 | -------------------------------------------------------------------------------- /Math Magic/Week16_FinalWeekWut.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 3, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import matplotlib.pyplot as plt\n", 10 | "import numpy as np\n", 11 | "import sympy" 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "metadata": {}, 17 | "source": [ 18 | "# Math Magic: Final Week Review\n", 19 | "![Party on](https://media.giphy.com/media/xU3xSF534t4ly/giphy.gif)" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "# Review: A bit of modern math philosophy" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "### What is the most elementary, simple, basic, primitive kind of math operation?" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "### What do you call it when you do a bunch of ^that kind of operation in a row?" 41 | ] 42 | }, 43 | { 44 | "cell_type": "markdown", 45 | "metadata": {}, 46 | "source": [ 47 | "### What do you call it when you do a bunch of ^that kind of operation in a row?" 48 | ] 49 | }, 50 | { 51 | "cell_type": "markdown", 52 | "metadata": {}, 53 | "source": [ 54 | "### Believe it or not, you can keep going down that road. If you do a bunch of ^that in a row, it is called `tetration`!" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "### A `hyperoperation` \n", 62 | "- The name for any `normal` operation (like the ones above).\n", 63 | "- This recursive repeated arithmetic operation can be described by:\n", 64 | "\n", 65 | "![SO HYPER](https://wikimedia.org/api/rest_v1/media/math/render/svg/2b5b37b38e6798ec67d72e429a051aa7641fb571)\n", 66 | "![Right?](https://media.giphy.com/media/t0Z2v0h7Vys2Q/giphy.gif)" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "metadata": {}, 72 | "source": [ 73 | "# Anyway, that's not even review. Back to the review!" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "metadata": {}, 79 | "source": [ 80 | "![triggrd](https://media.giphy.com/media/YEOLnB6lS4GA/giphy.gif)\n", 81 | "\"Drawing\"\n", 82 | "\n", 83 | "# 1. What is the sine of theta? $sin(\\theta) = ?$\n", 84 | "# 2. What is the cosine of theta? $cos(\\theta) = ?$\n", 85 | "# 3. What is the tangent of theta? $tan(\\theta) = ?$\n", 86 | "\n", 87 | "# 4. What is the arcsine (inverse sine) of y / r ? $arcsin(\\frac{y}{r}) = ?$\n", 88 | "# 5. What is the arccosine (inverse cosine) of x / r ? $arccos(\\frac{x}{r}) = ?$\n", 89 | "# 6. What is the arctangent (inverse tangent) of y / x? $arctan(\\frac{y}{x}) = ?$\n", 90 | "\n", 91 | "\"Drawing\"\n", 92 | "\n", 93 | "# 1. What the heck is this demonic drawing above?\n", 94 | "# 2. How many $\\pi$ radians is 0 degrees?\n", 95 | "# 3. How many $\\pi$ radians is 90 degrees?\n", 96 | "# 4. How many $\\pi$ radians is 270 degrees?\n", 97 | "\n", 98 | "# 5. Calculate in python the conversion between any *degrees* angle to *radians*" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 6, 104 | "metadata": {}, 105 | "outputs": [ 106 | { 107 | "data": { 108 | "text/plain": [ 109 | "0.7403686686959946" 110 | ] 111 | }, 112 | "execution_count": 6, 113 | "metadata": {}, 114 | "output_type": "execute_result" 115 | } 116 | ], 117 | "source": [ 118 | "# YOUR CODE HERE! Try converting degrees to radians \n", 119 | "\n", 120 | "degrees = 42.42 # convert me to radians!\n", 121 | "\n", 122 | "degrees * (2*np.pi/360)\n", 123 | "\n", 124 | "# HINT: use np.pi, it is a highly accurate pi" 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "metadata": {}, 130 | "source": [ 131 | "# Cowcooloose review\n", 132 | "\n", 133 | "![lolwut](https://media.giphy.com/media/vFKqnCdLPNOKc/giphy.gif)\n", 134 | "```\n", 135 | " /; ;\\\n", 136 | " __ \\____//\n", 137 | " /{_\\_/ `'\\____\n", 138 | " \\___ ---(=)--(=)--}\n", 139 | " _____________________________/ :--'\n", 140 | " ,-,'`@@@@@@@@ @@@@@@ \\_ `__\\\n", 141 | " ;:( @@@@@@@@@ @@@ \\___(o'o)\n", 142 | " :: ) @@@@ @@@@@@ ,'@@( `===='\n", 143 | " :: : @@@@@: @@@@ `@@@:\n", 144 | " :: \\ @@@@@: @@@@@@@) ( '@@@'\n", 145 | " ;; /\\ /`, @@@@@@@@@\\\\ :@@@@@)\n", 146 | " ::/ ) {_----------------: :~`, ;\n", 147 | " ;;'`; : ) : / `; ;\n", 148 | ";;;; : : ; : ; ; :\n", 149 | "`'`' / : : : : : :\n", 150 | " )_ \\__; \";\" :_ ; \\_\\ `,','\n", 151 | " :__\\ \\ * `,'* \\ \\ : \\ * 8`;'* *\n", 152 | " `^' \\ :/ `^' `-^-' \\v/ : \\/ -Bill Ames- \n", 153 | "```" 154 | ] 155 | }, 156 | { 157 | "cell_type": "markdown", 158 | "metadata": {}, 159 | "source": [ 160 | "### 1. What do we mean by the phrase \"rate of change\"?\n", 161 | "### 2. What do we call the \"rate of change\" of position?\n", 162 | "### 3. What do we call the \"rate of change\" of velocity/speed?\n", 163 | "### 4. What 1-word definition do we use for the phrase \"rate of change\"?\n", 164 | "\n", 165 | "### 5. What does this thing represent?\n", 166 | "## $\\frac{df(x)}{dx} = f'(x)$" 167 | ] 168 | }, 169 | { 170 | "cell_type": "markdown", 171 | "metadata": {}, 172 | "source": [ 173 | "# Recall that...\n", 174 | "## $x(t) = position$\n", 175 | "## $\\frac{dx(t)}{dt} = x'(t) = velocity$\n", 176 | "## $\\frac{dx^2(t)}{dt} = x''(t) = acceleration$" 177 | ] 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "metadata": {}, 182 | "source": [ 183 | "### 6. The function $f(x) = e^x$ is special for what reason?\n", 184 | "\n" 185 | ] 186 | }, 187 | { 188 | "cell_type": "markdown", 189 | "metadata": {}, 190 | "source": [ 191 | "# GUESS WHAT\n", 192 | "\n", 193 | "![You followin me?](https://media.giphy.com/media/WuGSL4LFUMQU/giphy.gif)\n", 194 | "\n", 195 | "# I THINK\n", 196 | "\n", 197 | "![hmm](https://media.giphy.com/media/kPtv3UIPrv36cjxqLs/giphy.gif)\n", 198 | "\n", 199 | "# WE WILL LEAVE IT AT THAT\n", 200 | "\n", 201 | "![yay](https://media.giphy.com/media/26n62j7cS0aZOYCu4/giphy.gif)" 202 | ] 203 | }, 204 | { 205 | "cell_type": "markdown", 206 | "metadata": {}, 207 | "source": [ 208 | "# Thank you for a very fun semester!\n", 209 | "- I hope you learned something useful!" 210 | ] 211 | }, 212 | { 213 | "cell_type": "code", 214 | "execution_count": null, 215 | "metadata": {}, 216 | "outputs": [], 217 | "source": [] 218 | } 219 | ], 220 | "metadata": { 221 | "kernelspec": { 222 | "display_name": "Python 3", 223 | "language": "python", 224 | "name": "python3" 225 | }, 226 | "language_info": { 227 | "codemirror_mode": { 228 | "name": "ipython", 229 | "version": 3 230 | }, 231 | "file_extension": ".py", 232 | "mimetype": "text/x-python", 233 | "name": "python", 234 | "nbconvert_exporter": "python", 235 | "pygments_lexer": "ipython3", 236 | "version": "3.6.5" 237 | } 238 | }, 239 | "nbformat": 4, 240 | "nbformat_minor": 2 241 | } 242 | -------------------------------------------------------------------------------- /Math Magic/Week8_PringlePlotter3000.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | ''' 4 | 5 | Your mission. 6 | If you choose to accept it... 7 | 8 | PLOT 9 | THE 10 | PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE 11 | 12 | Challenge 1 TABASCO SPICY: 13 | Try to figure out how to make the PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE 14 | niiiiiicee and smoooooth, not some rectangle piece of TRASH 15 | 16 | Challenge 2 HABANERO SPICY: 17 | Try to figure out how to change the color of it 18 | 19 | Challenge 3 GHOST PEPPER SPICYNESS: 20 | Give it a completely different shape, such as a chipotle bowl?!?! 21 | 22 | ''' 23 | 24 | # PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE equation is: 25 | # Z = X**2 - Y**2 !! OR !! Z = Y**2 - X**2 (spot the difference...) 26 | 27 | from mpl_toolkits.mplot3d import Axes3D # import the 3D thingy from matplotlib 28 | import matplotlib.pyplot as plt # import the plotter from matplotlib 29 | from matplotlib import cm # import matplotlib itself :O 30 | 31 | import numpy as np # import numpy, a really useful math / matrix package 32 | 33 | 34 | fig = plt.figure() # create a plot "figure" (window holding our PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE) 35 | ax = fig.gca(projection='3d') # tell the plot to be 3 dimensional 36 | 37 | # Make data. 38 | X = np.arange(-1, 1, 0.25) # from -1 to 1, at every .25 along the way 39 | Y = np.arange(-1, 1, 0.25) # from -1 to 1, at every .25 along the way 40 | X, Y = np.meshgrid(X, Y) # for every x, make a line of ys and vice-a-versa 41 | 42 | # Now, for every single X, Y pair, create a 3rd list, Z, which has the value 43 | # for Z of that X,Y pair. If (X,Y) = (2,3), then Z = (2**2 + 3**2) there! 44 | 45 | Z = X**2 - Y**2 46 | 47 | # Plot the PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE 48 | surf = ax.plot_surface( X, Y, Z, 49 | 50 | # give it some color ! 51 | # https://matplotlib.org/users/colormaps.html 52 | cmap=cm.coolwarm, 53 | linewidth=0, # how fat should the boundary lines be? 54 | antialiased=False, # make it niiiiiicee and smoooooth? 55 | ) 56 | 57 | # Customize the z axis. 58 | ax.set_zlim(-1.01, 1.01) 59 | 60 | # Add a color bar which maps values to colors. 61 | fig.colorbar(surf, shrink=0.5, aspect=5) 62 | 63 | # FYI, showing the PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE takes upwards of 30 sec 64 | plt.show() 65 | -------------------------------------------------------------------------------- /Math Magic/Week9_QuiverPlotter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | ============== 3 | 3D quiver plot 4 | ============== 5 | 6 | Demonstrates plotting directional arrows at points on a 3d meshgrid. 7 | 8 | YOUR MISSIONS, if you choose to accept them: 9 | 10 | JALAPENO. Change the size / dimensions of the vector positions 11 | TABASCO. Make a tornado shape 12 | SRIRACHA. Make a tornado shape with higher velocity at higher altitude 13 | PERI-PERI. Try adding more vectors, and measure the time it takes to add more 14 | - specifically, how many seconds per vector does it take? 15 | 16 | ''' 17 | 18 | from mpl_toolkits.mplot3d import axes3d 19 | import matplotlib.pyplot as plt 20 | import numpy as np 21 | 22 | fig = plt.figure() 23 | ax = fig.gca(projection='3d') # tell matplotlib we're doing a 3d plot 24 | 25 | # Make the grid of x y and z points 26 | x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2), 27 | np.arange(-0.8, 1, 0.2), 28 | np.arange(0, .1, 0.01)) 29 | 30 | # Make the direction data for each arrows at each x, y, z point 31 | # These are crazy equations. Try messing them up and see what happens!! :) 32 | 33 | # U is the x amount for EVERY vector at each X, Y, Z 34 | u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z) 35 | 36 | # V is the y component of EVERY vector at each X, Y, Z 37 | v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z) 38 | 39 | # W is the z component of EVERY vector at each X, Y, Z 40 | w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) * 41 | np.sin(np.pi * z)) 42 | 43 | # Do the "quiver" plot in 3d, given all of the data 44 | ax.quiver(x, y, z, u, v, w, 45 | 46 | length=0.1, # set the max length of vector 47 | normalize=False, # make all vectors same length? 48 | 49 | ) 50 | 51 | plt.show() 52 | -------------------------------------------------------------------------------- /Math Magic/__other__/Gravity.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import random 4 | import matplotlib.pyplot as plot 5 | from mpl_toolkits.mplot3d import Axes3D 6 | 7 | class point: 8 | def __init__(self, x,y,z): 9 | self.x = x 10 | self.y = y 11 | self.z = z 12 | 13 | class body: 14 | def __init__(self, location, mass, velocity, name = ""): 15 | self.location = location 16 | self.mass = mass 17 | self.velocity = velocity 18 | self.name = name 19 | 20 | def calculate_single_body_acceleration(bodies, body_index): 21 | G_const = 6.67408e-11 #m3 kg-1 s-2 22 | acceleration = point(0,0,0) 23 | target_body = bodies[body_index] 24 | for index, external_body in enumerate(bodies): 25 | if index != body_index: 26 | r = (target_body.location.x - external_body.location.x)**2 + (target_body.location.y - external_body.location.y)**2 + (target_body.location.z - external_body.location.z)**2 27 | r = math.sqrt(r) 28 | tmp = G_const * external_body.mass / r**3 29 | acceleration.x += tmp * (external_body.location.x - target_body.location.x) 30 | acceleration.y += tmp * (external_body.location.y - target_body.location.y) 31 | acceleration.z += tmp * (external_body.location.z - target_body.location.z) 32 | 33 | return acceleration 34 | 35 | def compute_velocity(bodies, time_step = 1): 36 | for body_index, target_body in enumerate(bodies): 37 | acceleration = calculate_single_body_acceleration(bodies, body_index) 38 | 39 | target_body.velocity.x += acceleration.x * time_step 40 | target_body.velocity.y += acceleration.y * time_step 41 | target_body.velocity.z += acceleration.z * time_step 42 | 43 | 44 | def update_location(bodies, time_step = 1): 45 | for target_body in bodies: 46 | target_body.location.x += target_body.velocity.x * time_step 47 | target_body.location.y += target_body.velocity.y * time_step 48 | target_body.location.z += target_body.velocity.z * time_step 49 | 50 | def compute_gravity_step(bodies, time_step = 1): 51 | compute_velocity(bodies, time_step = time_step) 52 | update_location(bodies, time_step = time_step) 53 | 54 | def plot_output(bodies, outfile = None): 55 | fig = plot.figure() 56 | colours = ['r','b','g','y','m','c'] 57 | ax = fig.add_subplot(1,1,1, projection='3d') 58 | max_range = 0 59 | for current_body in bodies: 60 | max_dim = max(max(current_body["x"]),max(current_body["y"]),max(current_body["z"])) 61 | if max_dim > max_range: 62 | max_range = max_dim 63 | ax.plot(current_body["x"], current_body["y"], current_body["z"], c = random.choice(colours), label = current_body["name"]) 64 | 65 | ax.set_xlim([-max_range,max_range]) 66 | ax.set_ylim([-max_range,max_range]) 67 | ax.set_zlim([-max_range,max_range]) 68 | ax.legend() 69 | 70 | if outfile: 71 | plot.savefig(outfile) 72 | else: 73 | plot.show() 74 | 75 | def run_simulation(bodies, names = None, time_step = 1, number_of_steps = 10000, report_freq = 100): 76 | 77 | #create output container for each body 78 | body_locations_hist = [] 79 | for current_body in bodies: 80 | body_locations_hist.append({"x":[], "y":[], "z":[], "name":current_body.name}) 81 | 82 | for i in range(1,number_of_steps): 83 | compute_gravity_step(bodies, time_step = 1000) 84 | 85 | if i % report_freq == 0: 86 | for index, body_location in enumerate(body_locations_hist): 87 | body_location["x"].append(bodies[index].location.x) 88 | body_location["y"].append(bodies[index].location.y) 89 | body_location["z"].append(bodies[index].location.z) 90 | 91 | return body_locations_hist 92 | 93 | #planet data (location (m), mass (kg), velocity (m/s) 94 | sun = {"location":point(0,0,0), "mass":2e30, "velocity":point(0,0,0)} 95 | mercury = {"location":point(0,5.7e10,0), "mass":3.285e23, "velocity":point(47000,0,0)} 96 | venus = {"location":point(0,1.1e11,0), "mass":4.8e24, "velocity":point(35000,0,0)} 97 | earth = {"location":point(0,1.5e11,0), "mass":6e24, "velocity":point(30000,0,0)} 98 | mars = {"location":point(0,2.2e11,0), "mass":2.4e24, "velocity":point(24000,0,0)} 99 | jupiter = {"location":point(0,7.7e11,0), "mass":1e28, "velocity":point(13000,0,0)} 100 | saturn = {"location":point(0,1.4e12,0), "mass":5.7e26, "velocity":point(9000,0,0)} 101 | uranus = {"location":point(0,2.8e12,0), "mass":8.7e25, "velocity":point(6835,0,0)} 102 | neptune = {"location":point(0,4.5e12,0), "mass":1e26, "velocity":point(5477,0,0)} 103 | pluto = {"location":point(0,7.29e9*1e3,0), "mass":1.3e22, "velocity":point(4748,0,0)} 104 | 105 | if __name__ == "__main__": 106 | 107 | #build list of planets in the simulation, or create your own 108 | bodies = [ 109 | body( location = pluto["location"], mass = pluto["mass"], velocity = pluto["velocity"], name = "pluto"), 110 | body( location = neptune["location"], mass = neptune["mass"], velocity = neptune["velocity"], name = "neptune"), 111 | body( location = uranus["location"], mass = uranus["mass"], velocity = uranus["velocity"], name = "uranus"), 112 | body( location = saturn["location"], mass = saturn["mass"], velocity = saturn["velocity"], name = "saturn"), 113 | body( location = jupiter["location"], mass = jupiter["mass"], velocity = jupiter["velocity"], name = "jupiter"), 114 | body( location = mars["location"], mass = mars["mass"], velocity = mars["velocity"], name = "mars"), 115 | body( location = earth["location"], mass = earth["mass"], velocity = earth["velocity"], name = "earth"), 116 | body( location = venus["location"], mass = venus["mass"], velocity = venus["velocity"], name = "venus"), 117 | body( location = mercury["location"], mass = mercury["mass"], velocity = mercury["velocity"], name = "mercury"), 118 | body( location = sun["location"], mass = sun["mass"], velocity = sun["velocity"], name = "sun"), 119 | ] 120 | 121 | motions = run_simulation(bodies, time_step = 100, number_of_steps = 80000, report_freq = 500) 122 | plot_output(motions, outfile = None)# 'orbits.png') 123 | -------------------------------------------------------------------------------- /Math Magic/__other__/Week9_solutions.py: -------------------------------------------------------------------------------- 1 | # TORNADO TIME 2 | u = z*u 3 | v = z*v 4 | w = z*w 5 | # As z gets to zero, u, v and w will be getting closer to zero too 6 | ## THE KEY TO MAKING THIS WORK IS normalize = FALSE below!! 7 | -------------------------------------------------------------------------------- /Math Magic/__other__/curve_fitting.py: -------------------------------------------------------------------------------- 1 | """ 2 | YOUR CHALLENGES... 3 | ...IF YOU ACCEPT THEM: 4 | 5 | (in order of SPICYNESS) 6 | · 7 | 1. TABASCO: Change the points to be different 8 | 2. SRIRACHA: Add more points - see if it can always fit all of them 9 | 3. HABANERO: Change the fit to a different fit algorithm 10 | 11 | 12 | """ 13 | 14 | 15 | import numpy as np 16 | import matplotlib.pyplot as plt 17 | 18 | # Create a couple of points 19 | points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)]) 20 | 21 | # Get the x and y lists ('vectors'): 22 | # x = [1,2,3,9]·· 23 | # y = [1,4,1,3] 24 | 25 | x = points[:,0] 26 | y = points[:,1] 27 | 28 | # calculate "polynomial" (curvy) fit 29 | z = np.polyfit(x, y, 3) 30 | f = np.poly1d(z) 31 | 32 | # calculate new x's and y's 33 | x_new = np.linspace(x[0], x[-1], 50) 34 | y_new = f(x_new) 35 | 36 | plt.plot(x,y,'o', x_new, y_new) 37 | plt.xlim([x[0]-1, x[-1] + 1 ]) 38 | plt.show() 39 | -------------------------------------------------------------------------------- /Math Magic/__other__/orbits.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonnyhyman/Programming-Classes/f56a9cf90e3b8e4aafad99644f1ed7e87ba14995/Math Magic/__other__/orbits.png -------------------------------------------------------------------------------- /Math Magic/untitled.txt: -------------------------------------------------------------------------------- 1 | JONNY IS SO RAD WOW -------------------------------------------------------------------------------- /Math You Will Actually Use/Week10_StarTrek.py: -------------------------------------------------------------------------------- 1 | import numpy as np # the first thing any starfleet officer does...! 2 | ''' 3 | Part 1: Romulans.........................! 4 | ''' 5 | x = 1000 # km 6 | y = 500 # km 7 | 8 | # since we can may treat the x and y as sides of a triangle, 9 | # we can use the pythagorean theorem to get the hypotenuse (range)! 10 | 11 | # range**2 = x**2 + y**2 12 | # range = + sqrt(x**2 + y**2) ORR!! - sqrt(x**2 + y**2) 13 | # although, the ship probably isn't behind us so ignore the negative sqrt... 14 | 15 | range = np.sqrt( np.power(x,2) + np.power(y,2) ) # power == ** ... KAPOW! 16 | mark = np.arctan(y / x) # reverse sin (y/x) 17 | mark = np.rad2deg(mark) 18 | 19 | print('Captain, the Romulan ship is', range,'kilometers, mark',mark,' and closing...') 20 | 21 | 22 | input('ENTER to continue') 23 | 24 | ''' 25 | Part 2: THE BORG AAAAHHHH! 26 | ''' 27 | 28 | mark0 = 65 # degrees 29 | mark1 = 55 # degrees 30 | diameter = 3 # kilometers 31 | 32 | # step 0: assume the borg ship is coming at you face-on 33 | # (no angling from your viewpoint)... Makes two triangle angles the same 34 | 35 | # step 1: split the (not-90-degree) triangle into two halves, so that 36 | # in the middle are two 90 degree triangles 37 | 38 | # step 2: figure out (mark0 - mark1)/2, the triangle's inner angle 39 | 40 | inner = (mark0 - mark1) / 2 41 | 42 | # step 3: sin = opp / hyp, in our case sin(inner) = (3km/2) / range 43 | # step 4: solve for range --> range = (diameter/2) / np.sin(np.deg2rad(inner)) 44 | # ......... you could use sympy in step 4 but I cheated and used paper ........ 45 | 46 | range = (diameter/2) / np.sin(np.deg2rad(inner)) 47 | 48 | print('Captain, the Borg ship is', range, 'kilometers and closing...') 49 | 50 | import webbrowser # shhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh 51 | webbrowser.open('https://media.giphy.com/media/tK3THRanG0d0c/giphy.gif') 52 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week11_Cowcooloose.py: -------------------------------------------------------------------------------- 1 | 2 | print( 3 | ''' 4 | 5 | Welcome to Cowcooloose, 6 | Here we will learn how cows are cool and often loosely correlated to math. 7 | 8 | /; ;\ 9 | __ \\____// 10 | /{_\_/ `'\____ 11 | \___ ---(=)--(=)--} 12 | _____________________________/ :--' 13 | ,-,'`@@@@@@@@ @@@@@@ \_ `__\ 14 | ;:( @@@@@@@@@ @@@ \___(o'o) 15 | :: ) @@@@ @@@@@@ ,'@@( `====' 16 | :: : @@@@@: @@@@ `@@@: 17 | :: \ @@@@@: @@@@@@@) ( '@@@' 18 | ;; /\ /`, @@@@@@@@@\ :@@@@@) 19 | ::/ ) {_----------------: :~`,~~; 20 | ;;'`; : ) : / `; ; 21 | ;;;; : : ; : ; ; : 22 | `'`' / : : : : : : 23 | )_ \__; ";" :_ ; \_\ `,',' 24 | :__\ \ * `,'* \ \ : \ * 8`;'* * 25 | `^' \ :/ `^' `-^-' \v/ : \/ -Bill Ames- 26 | 27 | 28 | ''' 29 | ) 30 | 31 | print( 32 | ''' 33 | A cow walks 3.2 miles in 1.5 hours. 34 | What is the speed of the cow in "mi/h"? 35 | 36 | Cows like imperial units btw... Weirdos... 37 | ''') 38 | 39 | ''' since dist = 3, and time = 1, and speed = distance / time, 40 | ''' 41 | 42 | ''' we'll use this later, don't mind it for now ''' 43 | def pause_continue(): 44 | print() 45 | input(' ... [ENTER] to continue') 46 | print('________________________') 47 | print() 48 | 49 | dist = 3.2 50 | time = 1.5 51 | 52 | speed = dist / time 53 | 54 | pause_continue() 55 | 56 | print('The cow walks at', speed, 'mi per hour') 57 | 58 | pause_continue() 59 | 60 | 61 | print(''' 62 | Now, what if as the cow walked, she accelerated (she's in a rush you see). 63 | If she sped up 1.2 mi per hour per hour, how fast is she going in 2 hrs? 64 | ''') 65 | 66 | accel = 1.2 # mi/hr per hr 67 | time = 2.0 68 | 69 | speed = speed + accel * time # mi/hr + (mi/hr)/hr * hr 70 | 71 | pause_continue() 72 | 73 | print('The cow walks at', speed, 'mi per hour after', time, 'hours') 74 | 75 | pause_continue() 76 | 77 | 78 | print(''' 79 | Now, more realistically, the cow will oscillate in speed... 80 | 81 | Let's use sine (y=sin(x)) to model how she changes speed... 82 | 83 | so, let's try speed = 2 * sin(time / 2) + 2 84 | 85 | IMPORTANT: Change of units for time, let time be in MINUTES 86 | 87 | ... What does that look like on a graph? 88 | ''') 89 | 90 | pause_continue() 91 | 92 | import sympy 93 | import numpy as np 94 | import matplotlib.pyplot as plt 95 | 96 | time = sympy.symbols('time') 97 | speed = 2 * sympy.sin(time * 200) + 2 98 | 99 | 100 | # lamdify() is a great function. 101 | # It turns sympy "symbolic" functions into real ones that can be USED! 102 | speed_numpy = sympy.lambdify( time, # speed(time) 103 | speed, # speed function (symbolic) 104 | modules=['numpy'] # use numpy's functions to make it real 105 | ) 106 | 107 | time_walking = 1.0 # spend 1 hour minutes walking 108 | times = np.linspace(0, time_walking, 100) # make 100 points between 0 and 60 109 | speeds = speed_numpy(times) # make 100 speeds at each time in times 110 | 111 | plt.plot(times, speeds) 112 | plt.xlabel("Time [minutes]") 113 | plt.ylabel("Cow Speed [mi/h]") 114 | plt.show() 115 | 116 | pause_continue() 117 | 118 | print(''' 119 | A trickier one now... How FAR does he walk in 60 minutes at this 120 | alternating speed? 121 | 122 | This is impossible to get perfect without calculus btw... 123 | ''') 124 | 125 | pause_continue() 126 | 127 | print(''' 128 | To do this, basically we do this: 129 | 130 | Figure out the Integral of Speed between time = 0 and time = 60 131 | 132 | What does that mean? 133 | 134 | In a nutshell it means to do this: 135 | 136 | for a ton of tiny slices of time (like really small, seriously): 137 | get the speed value at the start of that time slice 138 | 139 | take the speed * the width of the time slice 140 | (essentially get the area of the rectangle... 141 | (see whiteboard explanation for details)) 142 | 143 | add that speed*timewidth to a running total of areas 144 | 145 | at the end of it all, the total area gathered will be the 146 | amount of distance covered in that time... 147 | 148 | Isn't that kind of crazy? 149 | 150 | ------------------------- 151 | 152 | None of that actually matters, in practice, though. 153 | 154 | All you have to do is this: [see code] 155 | ''') 156 | 157 | # Remember, we already defined speed and time up above when we plotted 158 | 159 | distance = sympy.integrate(speed, (time, 0, time_walking) ) 160 | 161 | # evaluate result into a float (decimal number) 162 | distance_walked = distance.evalf() 163 | 164 | pause_continue() 165 | print('The cow walks a grand total of', distance_walked, 'miles in', 166 | time_walking, 'minutes') 167 | 168 | print("That's a fast cow!") 169 | print("Itd8fydts distance function is:", sympy.integrate(speed, time)) 170 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week11_EXPONENTIALDERIVATIVE.py: -------------------------------------------------------------------------------- 1 | import sympy 2 | 3 | x = sympy.Symbol('x') 4 | 5 | expression = sympy.exp(x) 6 | 7 | print() 8 | print() 9 | print(expression) 10 | 11 | derivative = sympy.diff(expression, x) 12 | 13 | print('derivative:', derivative) 14 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week12_OrbitsimReprise.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | A SPACESHIP ORBITAL SIMULATION - WITH REAL PHYSICS 4 | 5 | CHALLENGES (ordered by difficulty) 6 | 7 | Question: If ISS was orbiting around Mars, would it stay in orbit? 8 | 9 | Mars Gravity : -3.71 m/s^2 10 | Mars Mass : 6.39 * 1e23 kg 11 | Mars Radius : 3389 km 12 | 13 | Question: If a spaceship orbits at an altitude of 500km around Mars, 14 | what velocity does it need to stay in a mostly CIRCULAR orbit? 15 | 16 | Question: How much does Phobos, the innermost, largest moon of Mars, 17 | mess with the orbit of a spaceship in orbit at 1000km? 18 | 19 | Phobos Distance from Center of Mars: ~ 9300 km 20 | Phobos Radius : 11 km 21 | Phobos Mass : 1.0659 * 1e16 kg 22 | 23 | Question: How much change in velocity (delta-v) does that same spaceship 24 | need for its orbit to actually "intersect" the planet (barely) 25 | 26 | In otherwords, what is the difference in orbital velocity and 27 | maximum velocity required to impact the surface tangentially? 28 | 29 | ''' 30 | 31 | import matplotlib.pyplot as plt 32 | from time import time 33 | import numpy as np 34 | 35 | # First, enable interactive plotting 36 | plt.ion() # this fancy function makes a matplotlib window ALIIVEEEEE! 37 | 38 | # We want to draw the planet.... So let's do it in POLAR COORDINATES! 39 | # First we need some angles... 40 | # This gets 100 evenly spaced angles between 0 and 2pi 41 | circle_angles = np.linspace(0, (2*np.pi), 100) 42 | 43 | # ----------------------------- Getting planet set up 44 | R0 = 6371 * 1e3 # km * 1e3 => meters, radius of the planet 45 | 46 | planet_r = np.linspace(R0, R0, 100) # get 100 evenly spaced R0s 47 | planet_X = planet_r*np.cos(circle_angles) # X = take the cos(all_angles) * R0 48 | planet_Y = planet_r*np.sin(circle_angles) # Y = take the cos(all_angles) * R0 49 | planet = plt.plot(planet_X,planet_Y)[0] # make a plot with x and y 50 | 51 | # ----------------------------- Getting spaceship all set up 52 | 53 | ''' NOTE: numpy.arrays are used throughout. why? 54 | If you try [1,0,0] * 3 with Python lists, you'll get an error. 55 | If you try [1,0,0] * 3 with Numpy arrays, you'll get [3,0,0]... Useful! 56 | ''' 57 | 58 | 59 | alt_initial = 408_773 # ISS altitude, meters 60 | 61 | # let's start y = initial altitude + radius of planet 62 | pos_initial = np.array([ 63 | 0., 64 | alt_initial + R0 65 | ]) 66 | 67 | vel_initial = np.array([ 68 | 7666.736, 69 | 0. 70 | ]) # ISS horizontal velocity, meters per second 71 | 72 | 73 | trail_points = 500 # how many points should the trail keep? 74 | spaceship_trail = { 'x': [pos_initial[0]], 'y': [pos_initial[1]] } 75 | spaceship = plt.plot(*pos_initial)[0] # give plot the position intially 76 | 77 | # ----------------------------- Getting physics set up 78 | 79 | def gravity(pos): 80 | 81 | G = 6.674 * 1e-11 # universal gravitational constant 82 | M = 5.972 * 1e24 # mass of planet, kg 83 | 84 | # g = GM / r**2 85 | gravity_acceleration = G*M / (np.sqrt(pos[0]**2 + pos[1]**2))**2 86 | 87 | # which direction? 88 | # what vector tells us the direction of gravity? 89 | # the "down" vector of course! 90 | 91 | # also known as the negative of the position vector (normalized)! 92 | # pos / the magnitude of pos * gravity_acceleration at this alt 93 | g = (-pos/np.sqrt(pos[0]**2 + pos[1]**2)) * gravity_acceleration 94 | 95 | return g 96 | 97 | 98 | pos = pos_initial 99 | vel = vel_initial 100 | acc = gravity(pos) 101 | 102 | dt = 10 103 | 104 | while True: 105 | 106 | acc = gravity(pos) 107 | vel += (acc) * dt 108 | pos += (vel) * dt 109 | 110 | spaceship_trail['x'].append(pos[0]) 111 | spaceship_trail['y'].append(pos[1]) 112 | 113 | spaceship.set_xdata(spaceship_trail['x']) # get all the saved x data 114 | spaceship.set_ydata(spaceship_trail['y']) # get all the saved y data 115 | 116 | print('Trail N : ', len(spaceship_trail['x']), end =' | ') 117 | print('Altitude: ', round(np.linalg.norm(pos),2), end =' | ') 118 | print('Velocity: ', round(np.linalg.norm(vel),2), end =' | ') 119 | print('Gravity : ', round(np.linalg.norm(acc),2)) 120 | 121 | if len(spaceship_trail['x']) > trail_points: 122 | spaceship_trail['x'].pop(0) 123 | spaceship_trail['y'].pop(0) 124 | 125 | plt.pause(.01) 126 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week13_CarUncrashing.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Uh oh.. 4 | 5 | This car is headed straight for a brick wall... 6 | 7 | The driver is watching Netflix on his phone and will not see it in time... 8 | 9 | SAVE HIM!! (or not - he seriously shouldn't Netflix and drive I mean cmon) 10 | 11 | 12 | ... Oh, and once you're done saving him, try to do it while maintaining 13 | a speed of 100 mph! 14 | 15 | """ 16 | wheel_lp = 0 17 | throttle_lp = 0 18 | 19 | def control(actual_position, actual_velocity, dt): 20 | """ ALL OF YOUR CONTROL MAGICKS GO HERE """ 21 | global wheel_lp, throttle_lp 22 | 23 | y_desired = -50 24 | 25 | wheel_p = actual_position[1] - y_desired # proportional / error 26 | wheel_d = (wheel_p - wheel_lp) / dt # derivative 27 | wheel_lp = wheel_p 28 | 29 | wheel_command = 10.5*wheel_p + 100.0*wheel_d # +1 == turn right, full deflection 30 | 31 | speed_desired = 100 32 | throttle_p = -actual_velocity[0] + speed_desired # proportional / error 33 | throttle_d = (throttle_p - throttle_lp) / dt # derivative 34 | throttle_lp = throttle_p 35 | 36 | throttle_command = 1.8*throttle_p + 0.1*throttle_d # +1 == speed up 37 | 38 | 39 | return {'steer':wheel_command, 'throttle':throttle_command} 40 | 41 | 42 | # importing all the things 43 | import matplotlib.pyplot as plt 44 | from time import time 45 | import numpy as np 46 | 47 | from numpy.linalg import norm # norm is the same thing as sqrt(x**2 + y**2) 48 | 49 | 50 | # First, enable interactive plotting 51 | plt.ion() # this fancy function makes a matplotlib window ALIIVEEEEE! 52 | 53 | # Let's set some start variables! 54 | pos_initial = np.array([0., 0.]) 55 | vel_initial = np.array([30., 0.]) 56 | 57 | """ 58 | Why NUMPY arrays? 59 | If you try [1,2,3] - [4,5,6], you get a Python error (how to minus lists?) 60 | But! array([1,2,3]) - array([4,5,6]) = array([-3, -3, -3]) 61 | 62 | Pretty cool, eh? 63 | """ 64 | 65 | trail_points = 500 # how long do the car's tracks last? 66 | 67 | # Using a dictionary, we will store the entire trail of all points! 68 | car_trail = { 'x': [pos_initial[0]], 'y': [pos_initial[1]] } 69 | 70 | _ = plt.plot(1000, 0) # set the screen limits 71 | __ = plt.plot(1000, +100) # set the screen limits 72 | ___ = plt.plot(1000, -100) # set the screen limits 73 | 74 | car = plt.plot(np.array([0,0]))[0] # create the car! 75 | 76 | wall = plt.plot([500,500],[+100,-25])[0] # create the wall! 77 | 78 | accel_vect = plt.plot([0,0])[0] 79 | 80 | def car_physics(control, position, velocity): 81 | ''' These car physics are greatly exaggerated and simplified ''' 82 | 83 | # Control processing 84 | control['steer'] *= -np.pi/2 # 1 == turn 90 degrees (or try...) 85 | control['throttle'] *= 500 # exaggerated throttle 86 | 87 | 88 | direction = velocity / norm(velocity) # direction of travel, unit vector 89 | 90 | # F = m*a, which means a = F/m... F is throttle in our case 91 | car_mass = 100 # kg, average car mass 92 | motor_acceleration = control['throttle'] / car_mass 93 | 94 | # Not possible to steer more than about 45 degrees == pi/4 radians 95 | if control['steer'] > np.pi/2: 96 | control['steer'] = np.pi/2 97 | elif control['steer'] < -np.pi/2: 98 | control['steer'] = -np.pi/2 99 | 100 | 101 | # now, which direction are we accelerating into? 102 | # here, we are ROTATING the direction vector 103 | 104 | turn_direction = np.array([ 105 | + np.cos(control['steer']) * direction[0] 106 | - np.sin(control['steer']) * direction[1], # x rotated 107 | 108 | + np.sin(control['steer']) * direction[0] 109 | + np.cos(control['steer']) * direction[1], # y rotated 110 | ]) 111 | 112 | 113 | print('turn_direction', turn_direction, direction) 114 | 115 | 116 | 117 | ''' Friction on tires is more at higher speed ''' 118 | friction_coefficient = 0.1 # how much friction / mph? 119 | friction = velocity * friction_coefficient 120 | 121 | acceleration = motor_acceleration * turn_direction 122 | 123 | accel_vect.set_xdata([position[0], position[0] + 5*acceleration[0]]) 124 | accel_vect.set_ydata([position[1], position[1] + 5*acceleration[1]]) 125 | 126 | return acceleration - friction 127 | 128 | 129 | pos = pos_initial 130 | vel = vel_initial 131 | acc = car_physics({'steer':0, 'throttle':0}, pos, vel) 132 | 133 | while True: 134 | 135 | dt = .1 # how much time has passed ? delta-t / dt 136 | 137 | ctrl = control(pos, vel, dt) 138 | acc = car_physics(ctrl, pos, vel) 139 | vel += (acc) * dt 140 | pos += (vel) * dt 141 | 142 | 143 | car_trail['x'].append(pos[0]) 144 | car_trail['y'].append(pos[1]) 145 | 146 | car.set_xdata(car_trail['x']) # get all the saved x data 147 | car.set_ydata(car_trail['y']) # get all the saved y data 148 | 149 | #print('Trail N : ', len(car_trail['x']), end =' | ') 150 | #print('Distance: ', round(norm(pos),2), end =' | ') 151 | print('Velocity: ', round(norm(vel),2), end =' | ') 152 | #print('Steering: ', round(ctrl['steer'],2), end =' | ') 153 | #print('Throttle: ', round(ctrl['throttle'],2)) 154 | 155 | if len(car_trail['x']) > trail_points: 156 | car_trail['x'].pop(0) 157 | car_trail['y'].pop(0) 158 | 159 | plt.pause(.01) 160 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week15_AI.py: -------------------------------------------------------------------------------- 1 | """ 2 | Basic neural network lifted from : (and makde into python3) 3 | https://iamtrask.github.io/2015/07/12/basic-python-network/ 4 | 5 | Ordered by SPICYNESS 6 | 7 | Challenge 1 : Bell Pepper 8 | Change names of variables to more understandable ones (for you) 9 | 10 | Challenge 2 : Banana Pepper 11 | Change the test data (at the way bottom) to explore how well the 12 | network is trained 13 | 14 | Challenge 3 : Jalapeno 15 | Modify the number of training iterations to make the network better 16 | 17 | Challenge 4 : Cayenne pepper 18 | Add data to the network, by some pattern of your own choice, to make 19 | it classify that pattern 20 | 21 | Challenge 5 : Habanero 22 | Replace the nonlin function's "sigmoid" expressions with "tanh", 23 | which is the nonlinearity closer associated with human brain's 24 | activations: 25 | replace sigmoid with: 26 | (np.tanh(x) + 1)/2 27 | the derivative is: 28 | (1/2)*(1 - np.tanh(x) ** 2) 29 | 30 | Challenge 6 : Red Savina pepper 31 | Make a comparison of the sigmod and tanh activation "nonlin" functions. 32 | Which one works better for this kind of pattern? 33 | What about another pattern? 34 | 35 | Challenge 7 : Ghost Pepper / Carolina Reaper 36 | Add another layer to the network (would be l2) by following the pattern 37 | of how l1 is connected to l0 38 | 39 | """ 40 | import numpy as np 41 | 42 | # input dataset 43 | X = np.array([ 44 | [ord(character) for character in 'JON'], 45 | [ord(character) for character in 'BOB'], 46 | [ord(character) for character in 'JOE'], 47 | [ord(character) for character in 'JAK'], 48 | [ord(character) for character in 'ACK'], 49 | [ord(character) for character in 'JEF'], 50 | [ord(character) for character in 'DOM'], 51 | ]) 52 | 53 | # output dataset 54 | y = np.array([[1,0,1,1,0,1,0]]).T 55 | 56 | # sigmoid "squishification" function 57 | def nonlin(x, deriv=False): 58 | if (deriv == True): 59 | return (1/2)*(1 - np.tanh(x) ** 2) 60 | else: 61 | return (np.tanh(x) + 1)/2 62 | 63 | # seed random numbers to make calculation 64 | # deterministic (just a good practice) 65 | np.random.seed(1) 66 | 67 | # initialize weights randomly with mean 0 68 | syn0 = 2*np.random.random((X.shape[1],1)) - 1 69 | 70 | # training 71 | for iter in range(100_000_000): 72 | 73 | # forward propagation 74 | l0 = X 75 | 76 | l1 = nonlin(np.dot(l0,syn0)) 77 | 78 | # how much did we miss? 79 | l1_error = y - l1 80 | 81 | # multiply how much we missed by the 82 | # slope of the sigmoid at the values in l1 83 | l1_delta = l1_error * nonlin(l1, deriv = True) 84 | 85 | # update weights 86 | syn0 += np.dot(l0.T,l1_delta) 87 | 88 | print("Output After Training:") 89 | print(l1) 90 | 91 | # test dataset 92 | T = np.array([ [ord(character) for character in 'JAQ'], 93 | [ord(character) for character in 'CAJ'], 94 | [ord(character) for character in 'SUZ'], 95 | [ord(character) for character in 'OLV'], 96 | [ord(character) for character in 'KRS'], 97 | [ord(character) for character in 'JON'], 98 | [ord(character) for character in 'CAM'], 99 | ]) 100 | 101 | print("Test Set") 102 | print(T) 103 | 104 | l0 = T 105 | l1 = nonlin(np.dot(l0,syn0)) 106 | print("Test After Training") 107 | 108 | for val in l1: 109 | print(val) 110 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week2.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as jonnysradplots 2 | # "jonnysradplots" is an "alias" / temporary rename of "matplotlib.pyplot" 3 | 4 | xs = range(-50,50 +1) # [-50, -49, -48, ..., 48, 49, 50] 5 | # range() includes the start point, and NOT the end point, so do (start, end+1) 6 | 7 | def circle(x, whichhalf): # this thing is a function 8 | 9 | # equation is x**2 + y**2 = r**2 10 | # we solved for y, so that we have y = + (r**2 - x**2)**(1/2) for top half 11 | # and y = - (r**2 - x**2)**(1/2) for bot half 12 | 13 | radius = 42 14 | 15 | if whichhalf == 'top': 16 | return +( (radius)**2 - x**2) ** (1/2) # 1/2 exponent = square root 17 | else: 18 | return -( (radius)**2 - x**2) ** (1/2) 19 | 20 | tops = [] 21 | for x in xs: 22 | # add the circle point to the end of the top list 23 | point = circle(x, 'top') # assign to point what circle returns 24 | tops.append(point) 25 | 26 | bots = [] 27 | for x in xs: 28 | # add the circle point to the end of the bot list 29 | point = circle(x, 'bottom') # assign to point what circle returns 30 | bots.append(point) 31 | 32 | # These two lines are a more "Pythonic" way to do the exact same thing as above 33 | tops = [ circle(x, 'top') for x in xs] # "for each x, add circle(x) to tops" 34 | bots = [ circle(x, 'bottom') for x in xs] # "for each x, add circle(x) to bots" 35 | 36 | # Now, ladies and gentlemen, we plot! 37 | jonnysradplots.plot(xs,tops) # plot the tops 38 | jonnysradplots.plot(xs,bots) # plot the bots (in the same graph) 39 | jonnysradplots.show() # show the darn thing! 40 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week3_GraphingCalculator.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | # Let the user input an equation 4 | userTyped = input('Type your equation here! : ') 5 | 6 | xs = range(0, 100) # take a range of xs from 0 to 99 7 | 8 | ys = [] # get ready to fill ys 9 | for x in xs: 10 | # figure out the y value for this x 11 | y_value = userTyped.replace('x', str(x)) 12 | y_value = eval(y_value) # do the math 13 | ys.append(y_value) # add the y value to end of list 14 | 15 | plt.plot(xs, ys) 16 | plt.show() 17 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week4_AllInOneGraphingCalculator.py: -------------------------------------------------------------------------------- 1 | 2 | import matplotlib.pyplot as plt 3 | 4 | x0 = input("What x should we start at? >> " ) 5 | xf = input("What x should we end at? >> ") 6 | eq = input("Type your equation with x! >> " ) 7 | 8 | # assuming we get something like: 9 | # eq = '2*x' 10 | 11 | xs = range(int(x0), int(xf)+1) 12 | ys = [] 13 | 14 | for x in xs: 15 | 16 | y = eval(eq.replace('x', str(x))) 17 | ys.append(y) 18 | 19 | plt.plot(xs, ys) 20 | plt.show() 21 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week5_PringlePlotter3000.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | ''' 4 | 5 | Your mission. 6 | If you choose to accept it... 7 | 8 | PLOT 9 | THE 10 | PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE 11 | 12 | Challenge 1: 13 | Try to figure out how to make the PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE 14 | niiiiiicee and smoooooth, not some rectange piece of TRASH 15 | 16 | Challenge 2: 17 | Try to figure out how to change the color of it 18 | 19 | Challenge 3: 20 | Try to figure out how to make it CIRCULAR (from above) 21 | instead of some kind of rectangular piece of TRASH 22 | (these aren't pita chips, after all...) 23 | 24 | ''' 25 | 26 | # PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE equation is: 27 | # Z = X**2 - Y**2 !! OR !! Z = Y**2 - X**2 (spot the difference...) 28 | 29 | from mpl_toolkits.mplot3d import Axes3D # import the 3D thingy from matplotlib 30 | import matplotlib.pyplot as plt # import the plotter from matplotlib 31 | from matplotlib import cm # import matplotlib itself :O 32 | from matplotlib.ticker import LinearLocator, FormatStrFormatter 33 | # I have no clue what the above line does... 34 | 35 | import numpy as np # import numpy, a really useful math / matrix package 36 | 37 | 38 | fig = plt.figure() # create a plot "figure" (window holding our PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE) 39 | ax = fig.gca(projection='3d') # tell the plot to be 3 dimensional 40 | 41 | # Make data. 42 | X = np.arange(-1, 1, 0.1) # from -5 to 5, at every .25 along the way 43 | Y = np.arange(-1, 1, 0.1) # from -5 to 5, at every .25 along the way 44 | X, Y = np.meshgrid(X, Y) # for every x, make a line of ys and vice-a-versa 45 | 46 | make_circle_pringle = False # should we delete points outside of an XY circle? 47 | 48 | if make_circle_pringle: 49 | 50 | # Notice that the new surface when we do this is extremely jagged 51 | # Super ugly actually.... Why is this? 52 | 53 | X = np.where(X**2 + Y**2 <= 1, X, 0) 54 | Y = np.where(X**2 + Y**2 <= 1, Y, 0) 55 | 56 | # Because each time we get to one side, we teleport to the other side 57 | # and accidentally "drag the pen" along the way 58 | 59 | # Now, for every single X, Y pair, create a 3rd list, Z, which has the value 60 | # for Z of that X,Y pair. If (X,Y) = (2,3), then Z = (2**2 + 3**2) there! 61 | 62 | Z = X**2 - Y**2 63 | 64 | # Plot the PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE 65 | surf = ax.plot_surface( X, Y, Z, 66 | 67 | # give it some color ! 68 | # https://matplotlib.org/users/colormaps.html 69 | cmap=cm.coolwarm, 70 | linewidth=0, # how fat should the boundary lines be? 71 | antialiased=False, # make it niiiiiicee and smoooooth? 72 | ) 73 | 74 | # Customize the z axis. 75 | ax.set_zlim(-1.01, 1.01) 76 | ax.zaxis.set_major_locator(LinearLocator(10)) 77 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) 78 | 79 | # Add a color bar which maps values to colors. 80 | fig.colorbar(surf, shrink=0.5, aspect=5) 81 | 82 | # FYI, showing the PRINGLLLLLLEEEEEEEEEEEEEEEEEEEEE takes upwards of 30 sec 83 | plt.show() 84 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week6_QuiverPlotter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | ============== 3 | 3D quiver plot 4 | ============== 5 | 6 | Demonstrates plotting directional arrows at points on a 3d meshgrid. 7 | 8 | YOUR MISSION, if you choose to accept it: 9 | 10 | 1. Make a tornado shape 11 | 12 | 2. Make a tornado shape with higher velocity at higher altitude 13 | 14 | ''' 15 | 16 | from mpl_toolkits.mplot3d import axes3d 17 | import matplotlib.pyplot as plt 18 | import numpy as np 19 | 20 | fig = plt.figure() 21 | ax = fig.gca(projection='3d') # tell matplotlib we're doing a 3d plot 22 | 23 | # Make the grid of x y and z points 24 | x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2), 25 | np.arange(-0.8, 1, 0.2), 26 | np.arange(0, .1, 0.01)) 27 | 28 | # Make the direction data for each arrows at each x, y, z point 29 | # These are crazy equations. Try messing them up and see what happens!! :) 30 | 31 | # U is the x amount for EVERY vector at each X, Y, Z 32 | u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z) 33 | 34 | # V is the y component of EVERY vector at each X, Y, Z 35 | v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z) 36 | 37 | # W is the z component of EVERY vector at each X, Y, Z 38 | w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) * 39 | np.sin(np.pi * z)) 40 | 41 | 42 | # TORNADO TIME 43 | u = z*u 44 | v = z*v 45 | w = z*w 46 | # As z gets to zero, u, v and w will be getting closer to zero too 47 | ## THE KEY TO MAKING THIS WORK IS normalize = FALSE below!! 48 | 49 | # Do the "quiver" plot in 3d, given all of the data 50 | ax.quiver(x, y, z, u, v, w, 51 | 52 | length=0.1, # set the max length of vector 53 | normalize=False, # make all vectors same length? 54 | 55 | ) 56 | 57 | plt.show() 58 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week6_Sympy.py: -------------------------------------------------------------------------------- 1 | ' "pip install sympy" before you do any of this ' 2 | 3 | import sympy # import the calculator with variable buttons :) 4 | from sympy import Symbol 5 | 6 | # -------------------------- first, solve the simple equation 2*x=2 7 | x = Symbol('x') # create a "symoblic variable" x 8 | 9 | equation = 2*x - 2 # define the equation 2*x = 2 10 | 11 | solution = sympy.solve(equation, x) # solve for x 12 | 13 | print(solution) # print the list of all solutions 14 | 15 | # -------------------------- next, lets do the equation of a circle 16 | y = Symbol('y') 17 | 18 | equation = x**2 + y**2 - 1**2 # x**2 + y**2 = r**2 where r =1 19 | 20 | solution = sympy.solve(equation, y) # solve for y 21 | 22 | print(solution) 23 | 24 | # notice how one is the TOP half of the circle 25 | # and the other in the list is the BOTTOM half 26 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week7.py: -------------------------------------------------------------------------------- 1 | import sympy # import the calculator with variable buttons :) 2 | from sympy import Symbol, symbols 3 | 4 | # -------------------------- first, solve the simple equation 2*x=2 5 | x, y = symbols('x y') # plural 6 | 7 | # -------------------------- next, lets do the equation of a circle 8 | 9 | 10 | equation = 2**x + x*y**2 - 1 # x**2 + y**2 = r**2 where r =1 11 | 12 | solution = sympy.solve(equation, y) # solve for y 13 | 14 | print(solution) 15 | 16 | # notice how one is the TOP half of the circle 17 | # and the other in the list is the BOTTOM half 18 | phi 19 | e**z 20 | exp(z) 21 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week8_HowToTrig.py: -------------------------------------------------------------------------------- 1 | # THIS... 2 | # IS..... 3 | # TRIGGGGGGGGG! 4 | print(''' 5 | 6 | CONSIDER THE FOLLOWING... 7 | 8 | Imagine coordinates, x, and y 9 | 10 | |y 11 | | 12 | | 13 | -----------------------------x 14 | | 15 | | 16 | | 17 | 18 | What is the most glorious shape in the world? 19 | Why, a circle of course! 20 | 21 | I can't draw a circle with my keyboard (O, is that right??) 22 | So let's plot it 23 | 24 | 25 | OH, btw, we're making a circle with radius = 1 26 | 27 | There's an EXTREMELY FANCY WAY to explain to your fellow mathematicians 28 | that your circle has radius 1. You ready? The term is "UNIT". 29 | 30 | It is a UNIT circle if it has radius 1. 31 | 32 | ''') 33 | 34 | import matplotlib.pyplot as plt 35 | import numpy as np 36 | 37 | # Create the x axis, from -1 to 1, including 1 (linspace does this auto) 38 | 39 | xs = np.linspace(-1,1,100) # from -1 to 1, make 100 equally spaced points 40 | 41 | ys = {'top':[], 'bot':[]} # create a python dictionary holding the circle's ys 42 | 43 | # top half 44 | 45 | for x in xs: 46 | 47 | y_top = + np.sqrt( 1**2 - x**2) 48 | y_bot = - np.sqrt( 1**2 - x**2) 49 | 50 | ys['top'].append( y_top ) 51 | ys['bot'].append( y_bot ) 52 | 53 | plt.plot(xs, ys['top']) 54 | plt.plot(xs, ys['bot']) 55 | plt.show() 56 | 57 | print( 58 | ''' 59 | Now, all that was a bit tedious wasn't it? 60 | 61 | What if... 62 | 63 | What if we could just say "I WANT A UNIT CIRCLE THAT GOES AROUND ONCE", 64 | and it would just... WORK? 65 | 66 | Hmmm... 67 | 68 | In 'polar' coordinates, instead of using x and y as our "coordinates", 69 | we can just use "r" and "theta", or a "radius" and an "angle"........ 70 | 71 | So maybe we can just "sweep" over angles, and plot the radii? 72 | 73 | Something like... 74 | ''' 75 | 76 | 77 | ''' What is the circumference of a circle? 78 | 79 | ... I hope you remember... 80 | 81 | It's 2 * pi * radius.... Since our radius is 1, what's the circumference? 82 | 83 | 2*pi. SO! 84 | 85 | AHA! 86 | 87 | What if we just define our angles as fractions of the circumference? 88 | (instead of using degrees) 89 | 90 | So 0 degrees = 0 * 2*pi 91 | 92 | So 45 degrees = (2*pi / 8) = (pi / 4) <--> 45 deg 93 | 94 | So 90 degrees = (2*pi / 4) = (pi / 2) <--> 90 deg 95 | 96 | So 180 deg = (2*pi / 2) = (pi) <--> 180 deg 97 | 98 | So 360 deg = (2*pi / 1) = (2*pi) <--> 360 deg 99 | 100 | 101 | ... FYI these new fancy fractional angles are called 'radians' 102 | ''' 103 | ) 104 | 105 | from numpy import pi 106 | 107 | angles = np.linspace(0, 2*pi, 100) 108 | 109 | print(''' 110 | 111 | Okay, now how do to translate our new polar coordinates into xs and ys? 112 | (We need to do this so we can plot...) 113 | 114 | ''') 115 | 116 | # Here's how........ 117 | 118 | xs = np.cos(angles) # cosine maps an angle to an X value on the unit circle 119 | ys = np.sin(angles) # sine maps an angle to a Y value on the unit circle 120 | 121 | # tan = sin / cos ........ slope = y / x 122 | 123 | plt.plot(xs, ys) 124 | plt.show() 125 | 126 | print( 127 | ''' Well... That was easy. But what the heck is cos and sine? 128 | 129 | The answer is best seen by drawing triangles inside of circles. 130 | 131 | I shall explain on the white board...! 132 | 133 | ----------------------------------------- 134 | 135 | SOH : sin = opposite/hypotenuse 136 | CAH : cos = adjacent/hypotenuse 137 | TOA : tan = opposite/adjacent 138 | 139 | ----------------------------------------- 140 | 141 | Basically, 142 | 143 | x = cos(angle) works because cosine = adjacent / hypotenuse = x / 1 144 | y = sin(angle) works because cosine = opposite / hypotenuse = y / 1 145 | 146 | if we draw the triangle like this: 147 | 148 | /| 149 | hyp / | 150 | / | opposite side 151 | ---- 152 | adj 153 | 154 | where (angle) is measured between the adj and hypotenuse sides 155 | 156 | Notice also that: 157 | 158 | x**2 + y**2 = 1 159 | 160 | which means that 161 | 162 | cos(angle)**2 + sin(angle)**2 = 1 (for any angle) 163 | 164 | ''' 165 | ) 166 | 167 | print( 168 | ''' 169 | 170 | Congratulations! 171 | That's basically all of the really important stuff about trigonometry! 172 | 173 | 174 | If you ever want to get the ANGLE, and you know the LENGTH, 175 | 176 | use angle = arccos(length) = acos(length), or 177 | angle = arcsin(length) = asin(length), or 178 | angle = arctan(length) = atan(length), 179 | 180 | which will all work for a certain range of lengths (not all lengths...) 181 | 182 | Some extra tidbits: 183 | 184 | - There are these things called "trig identities"... 185 | - They are used like crazy in calculus and physics... 186 | - Basically, they boil down to equivalent ways to say exactly the same thing 187 | - If you want to see most of them, go here: 188 | https://en.wikipedia.org/wiki/List_of_trigonometric_identities 189 | 190 | ''' 191 | ) 192 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week9_1st_liveplotting.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | This is a quick demo for INTERACTIVE PLOTTING with Python / Matplotlib. 4 | 5 | We're going to plot a smiley face in real time. :) 6 | 7 | IMPORTANT: 8 | 9 | - I wrote this excessively lazily (way more code than needed) 10 | - I highlighted the important things that make it work with ********'s 11 | 12 | 13 | CHALLENGES (ordered by difficulty): 14 | 15 | Straightforward : change the amount of time it takes to plot 16 | Simple : change the color of the eyes to match 17 | SPICY : add a monacle, hat, or something else on the head 18 | SCARY : make the smiley face FROWN :( 19 | 20 | ''' 21 | import matplotlib.pyplot as plt 22 | 23 | import numpy as np 24 | from time import time 25 | 26 | # using polar coordinates because we are COOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOL 27 | 28 | seconds_to_draw = 5.0 29 | 30 | ''' ******** enable INTERACTIVE plotting ''' 31 | plt.ion() 32 | 33 | # get the axes set up with proper scaling! 34 | X, Y = np.linspace(-1, 1, 100), np.linspace(-1, 1, 100) 35 | 36 | ''' ******** add a line to the plot graphic''' 37 | head = plt.plot(X,Y)[0] 38 | smile = plt.plot(X,Y)[0] 39 | eyeL = plt.plot(X,Y)[0] 40 | eyeR = plt.plot(X,Y)[0] 41 | 42 | start = time() 43 | while True: 44 | 45 | amount = (time()-start)/seconds_to_draw 46 | 47 | if amount > 1: 48 | amount = 1 49 | 50 | # ---------- Head 51 | 52 | head_angle = np.linspace(0, (2*np.pi) * amount , 100) 53 | head_radii = np.linspace(1, 1, 100) 54 | 55 | X, Y = head_radii*np.cos(head_angle), head_radii*np.sin(head_angle) 56 | 57 | head.set_xdata(X) 58 | head.set_ydata(Y) 59 | 60 | # ---------- Smile 61 | 62 | smile_angle = np.linspace(- np.pi/4, 63 | -(np.pi/4)*(1-amount) - (3*np.pi/4) * amount, 100) 64 | smile_radii = np.linspace(.5, .5, 100) 65 | 66 | smileX = smile_radii*np.cos(smile_angle) 67 | smileY = smile_radii*np.sin(smile_angle) 68 | 69 | smile.set_xdata(smileX) 70 | smile.set_ydata(smileY) 71 | 72 | # ---------- Left eye 73 | 74 | eye_angle = np.linspace(0, 2*np.pi*amount, 100) 75 | eye_radii = np.linspace(.03, .03, 100) 76 | 77 | # offset so it's the correct side eyeball, not Mike Wazowski 78 | eye_X = eye_radii*np.cos(eye_angle) - .5 79 | eye_Y = eye_radii*np.sin(eye_angle) + .5 80 | 81 | eyeL.set_xdata(eye_X) 82 | eyeL.set_ydata(eye_Y) 83 | 84 | # ---------- Right eye 85 | 86 | eye_angle = np.linspace(0, 2*np.pi*amount, 100) 87 | eye_radii = np.linspace(.03, .03, 100) 88 | 89 | # offset so it's the correct side eyeball, not Mike Wazowski 90 | eye_X = eye_radii*np.cos(eye_angle) + .5 91 | eye_Y = eye_radii*np.sin(eye_angle) + .5 92 | 93 | eyeR.set_xdata(eye_X) 94 | eyeR.set_ydata(eye_Y) 95 | 96 | ''' ******** update the plots every .01 seconds ''' 97 | plt.pause(.01) 98 | -------------------------------------------------------------------------------- /Math You Will Actually Use/Week9_2nd_orbit_sim.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | A SPACESHIP ORBITAL SIMULATION - WITH REAL PHYSICS 4 | 5 | CHALLENGES (ordered by difficulty) 6 | 7 | Straightforward : mess around with the velocity. Try to get the spaceship to slingshot around earth's core 8 | Simple : print out the angle of the ship around earth as it orbits (hint arccos/arcsin/arctan) 9 | Simple : change the strength of gravity & try making it POSTIIVE :P 10 | 11 | SPICY : only track number of trail points based on how much time has passed 12 | SPICY : make the entire simulation REAL TIME 13 | SCARY : simulate the moon's gravitational pull on earth & the spaceship too 14 | OR SCARY : make the whole simulator 3D 15 | 16 | ''' 17 | 18 | import matplotlib.pyplot as plt 19 | from time import time 20 | import numpy as np 21 | 22 | # First, enable interactive plotting 23 | plt.ion() 24 | 25 | # get 100 evenly spaced angles between 0 and 2pi 26 | circle_angles = np.linspace(0, (2*np.pi), 100) 27 | 28 | # ----------------------------- Getting earth set up 29 | R0 = 6371 * 1e3 # kilometers, radius of the earth 30 | 31 | 32 | earth_r = np.linspace(R0, R0, 100) # get 100 evenly spaced R0s 33 | earth_X = earth_r*np.cos(circle_angles) # X = take the cos(all_angles) * R0 34 | earth_Y = earth_r*np.sin(circle_angles) # Y = take the cos(all_angles) * R0 35 | earth = plt.plot(earth_X,earth_Y)[0] # make a plot with x and y 36 | 37 | # ----------------------------- Getting spaceship all set up 38 | 39 | ''' NOTE: numpy.arrays are used throughout. why? 40 | If you try [1,0,0] * 3 with Python lists, you'll get an error. 41 | If you try [1,0,0] * 3 with Numpy arrays, you'll get [3,0,0]... Useful! 42 | ''' 43 | 44 | 45 | alt_initial = 408_773 # ISS altitude, meters 46 | 47 | # let's start y = initial altitude + radius of earth 48 | pos_initial = np.array([ 49 | 0., 50 | alt_initial + R0 51 | ]) 52 | 53 | vel_initial = np.array([ 54 | 7666.736, 55 | 0. 56 | ]) # ISS horizontal velocity, meters 57 | 58 | 59 | trail_points = 500 # how many points should the trail keep? 60 | spaceship_trail = { 'x': [pos_initial[0]], 'y': [pos_initial[1]] } 61 | spaceship = plt.plot(*pos_initial)[0] # give plot the position intially 62 | 63 | # ----------------------------- Getting physics set up 64 | 65 | gravity_acceleration = -9.81 # m/s 66 | 67 | def gravity(pos): 68 | 69 | G = 6.674 * 1e-11 # universal gravitational constant 70 | M = 5.972 * 1e24 # mass of earth 71 | 72 | # g = GM / r**2 73 | gravity_acceleration = G*M / (np.sqrt(pos[0]**2 + pos[1]**2))**2 74 | 75 | # which direction? 76 | # what vector tells us the direction of gravity? 77 | # the "down" vector of course! 78 | 79 | # also known as the negative of the position vector (normalized)! 80 | # pos / the magnitude of pos * gravity_acceleration at this alt 81 | g = (-pos/np.sqrt(pos[0]**2 + pos[1]**2)) * gravity_acceleration 82 | 83 | return g 84 | 85 | 86 | pos = pos_initial 87 | vel = vel_initial 88 | acc = gravity(pos) 89 | 90 | dt = 10 91 | 92 | while True: 93 | 94 | acc = gravity(pos) 95 | vel += (acc) * dt 96 | pos += (vel) * dt 97 | 98 | spaceship_trail['x'].append(pos[0]) 99 | spaceship_trail['y'].append(pos[1]) 100 | 101 | spaceship.set_xdata(spaceship_trail['x']) # get all the saved x data 102 | spaceship.set_ydata(spaceship_trail['y']) # get all the saved y data 103 | 104 | print('Trail N : ', len(spaceship_trail['x']), end =' | ') 105 | print('Altitude: ', round(np.linalg.norm(pos),2), end =' | ') 106 | print('Velocity: ', round(np.linalg.norm(vel),2), end =' | ') 107 | print('Gravity : ', round(np.linalg.norm(acc),2)) 108 | 109 | if len(spaceship_trail['x']) > trail_points: 110 | spaceship_trail['x'].pop(0) 111 | spaceship_trail['y'].pop(0) 112 | 113 | plt.pause(.01) 114 | -------------------------------------------------------------------------------- /Math You Will Actually Use/__secrets__/Week13_Solution.py: -------------------------------------------------------------------------------- 1 | # Super ultra simple wheel command solution 2 | wheel_command = ((-50) - actual_position[1])*0.1 - actual_velocity[1] 3 | 4 | 5 | # Better 6 | cp = +0.1 7 | cd = -1.0 8 | error = (-50) - actual_position[1]) 9 | wheel_command = cp * error + cd * actual_velocity[1] 10 | -------------------------------------------------------------------------------- /Python Projects/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonnyhyman/Programming-Classes/f56a9cf90e3b8e4aafad99644f1ed7e87ba14995/Python Projects/.DS_Store -------------------------------------------------------------------------------- /Python Projects/ASSERT.py: -------------------------------------------------------------------------------- 1 | class Hendrick: 2 | def __init__(self): 3 | self.value = None 4 | 5 | h0 = Hendrick() 6 | h1 = Hendrick() 7 | 8 | h0.value = int(1) 9 | h1.value = float(1.0) 10 | print(h0.value == h1.value) 11 | print(h0.value is h1.value) 12 | -------------------------------------------------------------------------------- /Python Projects/AUDIOSIMULTANEOUS.py: -------------------------------------------------------------------------------- 1 | import PyAudioMixer as pam 2 | from time import time 3 | import wave 4 | 5 | #import pdb; pdb.set_trace() 6 | 7 | mixer = pam.Mixer() 8 | mixer.start() 9 | snd = pam.Sound(mixer, filename="Cs5.wav") 10 | snd1 = pam.Sound(mixer, filename="Gs5.wav") 11 | 12 | 13 | snd.play() 14 | 15 | notstarted = True 16 | start = time() 17 | while True: 18 | 19 | if time()-start > 1 and notstarted: 20 | print('STARTED1') 21 | snd1.play() 22 | print('STARTED2') 23 | notstarted = False 24 | -------------------------------------------------------------------------------- /Python Projects/AutoTyper.py: -------------------------------------------------------------------------------- 1 | # This is a python module called PyQt5 2 | 3 | from PyQt5 import QtGui, QtCore, QtWidgets 4 | import sys 5 | 6 | app = QtWidgets.QApplication(sys.argv) # create an app object 7 | 8 | class Window(QtWidgets.QMainWindow): 9 | 10 | def __init__(self): 11 | super(Window,self).__init__() 12 | self.setFixedSize(400,400) 13 | 14 | self.setWindowTitle("THIS IS THE RADDEST WINDOW EVERRRRR") 15 | 16 | self.centralWidget = QtWidgets.QWidget() 17 | self.setCentralWidget(self.centralWidget) 18 | 19 | self.button = QtWidgets.QPushButton('BUTTON', self.centralWidget) 20 | self.button.clicked.connect(self.pressed) 21 | 22 | self.text = QtWidgets.QTextEdit(self.centralWidget) 23 | self.text.setGeometry(10,50,200,200) 24 | 25 | self.thingwewannatype = 'THISSTUFF' 26 | 27 | self.n = 1 28 | 29 | def pressed(self, event): 30 | # start the timer to type the thing 31 | print('SPACE CODE') 32 | self.timer = QtCore.QTimer(self) 33 | self.timer.timeout.connect(self.typer) 34 | self.timer.start(300) 35 | 36 | def typer(self): 37 | 38 | currenttext = self.thingwewannatype[:self.n] 39 | self.text.setText(currenttext) 40 | self.n += 1 41 | 42 | gui = Window() 43 | gui.show() 44 | app.exec_() # do the application 45 | -------------------------------------------------------------------------------- /Python Projects/Cs5.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonnyhyman/Programming-Classes/f56a9cf90e3b8e4aafad99644f1ed7e87ba14995/Python Projects/Cs5.wav -------------------------------------------------------------------------------- /Python Projects/Filedownload.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "ename": "SyntaxError", 10 | "evalue": "invalid syntax (, line 3)", 11 | "output_type": "error", 12 | "traceback": [ 13 | "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m name =\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" 14 | ] 15 | } 16 | ], 17 | "source": [ 18 | "import urllib.request\n", 19 | "\n", 20 | "name = \"C5\" \n", 21 | "link = f\"http://asdfasdfasdfsdfadfs/Piano.ff.{name}.aiff\"\n", 22 | "\n", 23 | "data = urllib.request.urlopen(link).read() \n", 24 | "\n", 25 | "with open(f\"{name}.aiff\", \"wb\") as file:\n", 26 | " file.write(data)" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 3, 32 | "metadata": {}, 33 | "outputs": [ 34 | { 35 | "data": { 36 | "text/plain": [ 37 | "'What is 1/5 = 0.2'" 38 | ] 39 | }, 40 | "execution_count": 3, 41 | "metadata": {}, 42 | "output_type": "execute_result" 43 | } 44 | ], 45 | "source": [ 46 | "stringy = f\"What is 1/5 = {1/5}\"\n", 47 | "stringy" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 4, 53 | "metadata": {}, 54 | "outputs": [ 55 | { 56 | "name": "stdout", 57 | "output_type": "stream", 58 | "text": [ 59 | "Collecting soundfile\n", 60 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/d2/06/58d71f2041bc89919f56a69f8f2b9535a55d513bb005fbe4f8ee5d367170/SoundFile-0.10.2-py2.py3.cp26.cp27.cp32.cp33.cp34.cp35.cp36.pp27.pp32.pp33-none-macosx_10_5_x86_64.macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.whl (616kB)\n", 61 | "\u001b[K 100% |████████████████████████████████| 624kB 6.8MB/s \n", 62 | "\u001b[?25hRequirement already satisfied: cffi>=1.0 in /Users/jonny/anaconda3/lib/python3.6/site-packages (from soundfile) (1.11.5)\n", 63 | "Requirement already satisfied: pycparser in /Users/jonny/anaconda3/lib/python3.6/site-packages (from cffi>=1.0->soundfile) (2.18)\n", 64 | "Installing collected packages: soundfile\n", 65 | "Successfully installed soundfile-0.10.2\n", 66 | "\u001b[33mYou are using pip version 18.0, however version 19.0.1 is available.\n", 67 | "You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n" 68 | ] 69 | } 70 | ], 71 | "source": [ 72 | "!pip install soundfile" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": 6, 78 | "metadata": {}, 79 | "outputs": [ 80 | { 81 | "name": "stdout", 82 | "output_type": "stream", 83 | "text": [ 84 | "0\n", 85 | "1\n", 86 | "2\n", 87 | "3\n", 88 | "4\n", 89 | "5\n", 90 | "6\n", 91 | "7\n", 92 | "8\n", 93 | "9\n" 94 | ] 95 | } 96 | ], 97 | "source": [ 98 | "from time import time\n", 99 | "\n", 100 | "start = time()\n", 101 | "\n", 102 | "for _ in range(10):\n", 103 | " print(_)\n", 104 | " \n", 105 | " if time() - start > .5:\n", 106 | " start = time()\n", 107 | " # DO YOUR THING\n", 108 | " print('BEEP')" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": null, 114 | "metadata": {}, 115 | "outputs": [], 116 | "source": [] 117 | } 118 | ], 119 | "metadata": { 120 | "kernelspec": { 121 | "display_name": "Python 3", 122 | "language": "python", 123 | "name": "python3" 124 | }, 125 | "language_info": { 126 | "codemirror_mode": { 127 | "name": "ipython", 128 | "version": 3 129 | }, 130 | "file_extension": ".py", 131 | "mimetype": "text/x-python", 132 | "name": "python", 133 | "nbconvert_exporter": "python", 134 | "pygments_lexer": "ipython3", 135 | "version": "3.6.5" 136 | } 137 | }, 138 | "nbformat": 4, 139 | "nbformat_minor": 2 140 | } 141 | -------------------------------------------------------------------------------- /Python Projects/Gs5.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonnyhyman/Programming-Classes/f56a9cf90e3b8e4aafad99644f1ed7e87ba14995/Python Projects/Gs5.wav -------------------------------------------------------------------------------- /Python Projects/HendricksTyper.py: -------------------------------------------------------------------------------- 1 | # This is a python module called PyQt5 2 | 3 | from PyQt5 import QtGui, QtCore, QtWidgets 4 | import sys 5 | 6 | app = QtWidgets.QApplication(sys.argv) # create an app object 7 | 8 | class Window(QtWidgets.QMainWindow): 9 | 10 | def __init__(self): 11 | super(Window,self).__init__() 12 | self.setFixedSize(400,400) 13 | 14 | self.setWindowTitle("THIS IS THE RADDEST WINDOW EVERRRRR") 15 | 16 | self.centralWidget = QtWidgets.QWidget() 17 | self.setCentralWidget(self.centralWidget) 18 | 19 | self.button = QtWidgets.QPushButton('BUTTON', self.centralWidget) 20 | self.button.clicked.connect(self.pressed) 21 | 22 | self.text = QtWidgets.QTextEdit(self.centralWidget) 23 | self.text.setGeometry(10,50,200,200) 24 | 25 | self.thingwewannatype = 'THISSTUFF' 26 | 27 | self.n = 1 28 | 29 | def pressed(self, event): 30 | # start the timer to type the thing 31 | print('SPACE CODE') 32 | self.timer = QtCore.QTimer(self) 33 | self.timer.timeout.connect(self.typer) 34 | self.timer.start(300) 35 | 36 | def typer(self): 37 | 38 | currenttext = self.thingwewannatype[:self.n] 39 | self.text.setText(currenttext) 40 | self.n += 1 41 | 42 | gui = Window() 43 | gui.show() 44 | app.exec_() # do the application 45 | -------------------------------------------------------------------------------- /Python Projects/PDB.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | x = 1 4 | 5 | import pdb 6 | pdb.set_trace() 7 | 8 | x = 2 9 | -------------------------------------------------------------------------------- /Python Projects/QtGraphics.py: -------------------------------------------------------------------------------- 1 | from PyQt5 import QtGui, QtCore, QtWidgets 2 | import sys 3 | 4 | Window = QtWidgets.QMainWindow 5 | Brush = QtGui.QBrush 6 | Pen = QtGui.QPen 7 | 8 | Color = QtGui.QColor 9 | Stage = QtWidgets.QGraphicsScene 10 | 11 | ImageItem = QtWidgets.QGraphicsPixmapItem 12 | Image = QtGui.QPixmap 13 | 14 | class View(QtWidgets.QGraphicsView): 15 | def __init__(self, stage): 16 | super().__init__(stage) 17 | self.stage = stage 18 | 19 | i = Image('moon.jpg') 20 | i = i.scaledToHeight(600) 21 | 22 | self.stage.addItem(ImageItem(i)) 23 | 24 | if __name__=='__main__': 25 | 26 | app = QtWidgets.QApplication(sys.argv) 27 | 28 | stage = Stage(0, 0, 800, 600) 29 | view = View(stage) 30 | view.show() 31 | 32 | app.exec_() # complete all execution code in the GUI 33 | -------------------------------------------------------------------------------- /Python Projects/QtMagic.py: -------------------------------------------------------------------------------- 1 | 2 | from PyQt5 import QtGui, QtCore, QtWidgets 3 | import sys 4 | 5 | from Crazystuff import * 6 | 7 | class GO(Window): 8 | 9 | 10 | def __init__(self): 11 | super().__init__() 12 | 13 | v = View(600, 600, parent = self) 14 | 15 | self.setFixedSize(v.width(), v.height()) 16 | 17 | rect = v.stage.addRect(GetRekt(0,0,100,100)) 18 | 19 | rect.setBrush(Brush(Color(255,0,0,))) 20 | rect.setPen(Pen(Color(0,0,255))) 21 | 22 | self.show() 23 | 24 | class View(GView): 25 | 26 | def __init__(self, w, h, parent=None): 27 | 28 | 29 | # stage is the scene, for holding object trees 30 | self.stage = Stage(0, 0, w, h, parent) 31 | 32 | # init QGraphicsView 33 | super(View, self).__init__(self.stage, parent) 34 | 35 | self.setGeometry(0,0, w, h) 36 | 37 | 38 | if __name__ == '__main__': 39 | 40 | app = QtWidgets.QApplication(sys.argv) 41 | gui = GO() 42 | 43 | sys.exit(app.exec_()) 44 | -------------------------------------------------------------------------------- /Python Projects/SAMSRADTHINGY.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 8, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import cv2\n", 10 | "import numpy as np" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 16, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "class CVNumber:\n", 20 | " \n", 21 | " def __init__(self, value):\n", 22 | " self.value = value \n", 23 | " \n", 24 | " def __add__(self, other):\n", 25 | " return cv2.add(self.value, other.value) \n", 26 | " \n", 27 | " def __sub__(self, other):\n", 28 | " return cv2.add(self.value, -other.value) \n", 29 | " \n", 30 | " def __mul__(self, other):\n", 31 | " pass\n", 32 | " \n", 33 | " def __rmul__(self, other):\n", 34 | " pass\n", 35 | " \n", 36 | " def __div__(self, other):\n", 37 | " pass\n", 38 | " \n", 39 | " def __rdiv__(self, other):\n", 40 | " pass" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 17, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "x = np.uint8([250])\n", 50 | "y = np.uint8([10])" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": 18, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "x = CVNumber(x)\n", 60 | "y = CVNumber(y)" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 19, 66 | "metadata": {}, 67 | "outputs": [ 68 | { 69 | "data": { 70 | "text/plain": [ 71 | "array([250], dtype=uint8)" 72 | ] 73 | }, 74 | "execution_count": 19, 75 | "metadata": {}, 76 | "output_type": "execute_result" 77 | } 78 | ], 79 | "source": [ 80 | "x.value" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": 14, 86 | "metadata": {}, 87 | "outputs": [ 88 | { 89 | "data": { 90 | "text/plain": [ 91 | "array([10], dtype=uint8)" 92 | ] 93 | }, 94 | "execution_count": 14, 95 | "metadata": {}, 96 | "output_type": "execute_result" 97 | } 98 | ], 99 | "source": [ 100 | "y.value" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": 20, 106 | "metadata": {}, 107 | "outputs": [ 108 | { 109 | "data": { 110 | "text/plain": [ 111 | "array([[255]], dtype=uint8)" 112 | ] 113 | }, 114 | "execution_count": 20, 115 | "metadata": {}, 116 | "output_type": "execute_result" 117 | } 118 | ], 119 | "source": [ 120 | "x + y" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [ 129 | "cv2.add()" 130 | ] 131 | } 132 | ], 133 | "metadata": { 134 | "kernelspec": { 135 | "display_name": "Python 3", 136 | "language": "python", 137 | "name": "python3" 138 | }, 139 | "language_info": { 140 | "codemirror_mode": { 141 | "name": "ipython", 142 | "version": 3 143 | }, 144 | "file_extension": ".py", 145 | "mimetype": "text/x-python", 146 | "name": "python", 147 | "nbconvert_exporter": "python", 148 | "pygments_lexer": "ipython3", 149 | "version": "3.6.5" 150 | } 151 | }, 152 | "nbformat": 4, 153 | "nbformat_minor": 2 154 | } 155 | -------------------------------------------------------------------------------- /Python Projects/Untitled.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 19, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "ename": "ModuleNotFoundError", 10 | "evalue": "No module named 'scikits'", 11 | "output_type": "error", 12 | "traceback": [ 13 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 14 | "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", 15 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mscikits\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0maudiolab\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0maudiolab\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mframes1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfs1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mencoder1\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0maudiolab\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwavread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Cs5.wav'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mframes2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfs2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mencoder2\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0maudiolab\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwavread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Cs5.wav'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mmixed\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mframes1\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mframes2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", 16 | "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'scikits'" 17 | ] 18 | } 19 | ], 20 | "source": [ 21 | "\"\"\"PyAudio Example: Play a wave file.\"\"\"\n", 22 | "\n", 23 | "from multiprocessing import Process\n", 24 | "\n", 25 | "import pyaudio\n", 26 | "import wave\n", 27 | "import sys\n", 28 | "\n", 29 | "CHUNK = 1024\n", 30 | "\n", 31 | "wf = wave.open(wavename, 'rb')\n", 32 | "\n", 33 | "# instantiate PyAudio (1)\n", 34 | "p = pyaudio.PyAudio()\n", 35 | "\n", 36 | "# open stream (2)\n", 37 | "stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),\n", 38 | " channels=wf.getnchannels(),\n", 39 | " rate=wf.getframerate(),\n", 40 | " output=True)\n", 41 | "\n", 42 | "# read data\n", 43 | "data = wf.readframes(CHUNK)\n", 44 | "\n", 45 | "# play stream (3)\n", 46 | "while len(data) > 0:\n", 47 | " stream.write(data)\n", 48 | " data = wf.readframes(CHUNK)\n", 49 | "\n", 50 | "# stop stream (4)\n", 51 | "stream.stop_stream()\n", 52 | "stream.close()\n", 53 | "\n", 54 | "# close PyAudio (5)\n", 55 | "p.terminate()" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": 18, 61 | "metadata": {}, 62 | "outputs": [ 63 | { 64 | "name": "stderr", 65 | "output_type": "stream", 66 | "text": [ 67 | "Process Process-2:\n", 68 | "Traceback (most recent call last):\n", 69 | " File \"/Users/jonny/anaconda3/lib/python3.6/multiprocessing/process.py\", line 258, in _bootstrap\n", 70 | " self.run()\n", 71 | " File \"/Users/jonny/anaconda3/lib/python3.6/multiprocessing/process.py\", line 93, in run\n", 72 | " self._target(*self._args, **self._kwargs)\n", 73 | " File \"\", line 22, in playthis\n", 74 | " output=True)\n", 75 | " File \"/Users/jonny/anaconda3/lib/python3.6/site-packages/pyaudio.py\", line 750, in open\n", 76 | " stream = Stream(self, *args, **kwargs)\n", 77 | " File \"/Users/jonny/anaconda3/lib/python3.6/site-packages/pyaudio.py\", line 441, in __init__\n", 78 | " self._stream = pa.open(**arguments)\n", 79 | "OSError: [Errno -9996] Invalid output device (no default output device)\n" 80 | ] 81 | } 82 | ], 83 | "source": [ 84 | "P.start()" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [] 93 | } 94 | ], 95 | "metadata": { 96 | "kernelspec": { 97 | "display_name": "Python 3", 98 | "language": "python", 99 | "name": "python3" 100 | }, 101 | "language_info": { 102 | "codemirror_mode": { 103 | "name": "ipython", 104 | "version": 3 105 | }, 106 | "file_extension": ".py", 107 | "mimetype": "text/x-python", 108 | "name": "python", 109 | "nbconvert_exporter": "python", 110 | "pygments_lexer": "ipython3", 111 | "version": "3.6.5" 112 | } 113 | }, 114 | "nbformat": 4, 115 | "nbformat_minor": 2 116 | } 117 | -------------------------------------------------------------------------------- /Python Projects/Untitled1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "def funk(a,b,c):\n", 10 | " print(a,b,c)" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 2, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "AB = ('blah', 'bloo')\n", 20 | "C = 'blump'" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 4, 26 | "metadata": {}, 27 | "outputs": [ 28 | { 29 | "name": "stdout", 30 | "output_type": "stream", 31 | "text": [ 32 | "blah bloo blump\n" 33 | ] 34 | } 35 | ], 36 | "source": [ 37 | "funk(*AB, C)" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 6, 43 | "metadata": {}, 44 | "outputs": [ 45 | { 46 | "name": "stdout", 47 | "output_type": "stream", 48 | "text": [ 49 | "[' over ', ' get ', ' here! ', ' please ']\n" 50 | ] 51 | } 52 | ], 53 | "source": [ 54 | "import random\n", 55 | "jonny = [\" please \",\" get \",\" over \",\" here! \"]\n", 56 | "random.shuffle(jonny)\n", 57 | "print(jonny)" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": null, 63 | "metadata": {}, 64 | "outputs": [], 65 | "source": [] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [] 80 | } 81 | ], 82 | "metadata": { 83 | "kernelspec": { 84 | "display_name": "Python 3", 85 | "language": "python", 86 | "name": "python3" 87 | }, 88 | "language_info": { 89 | "codemirror_mode": { 90 | "name": "ipython", 91 | "version": 3 92 | }, 93 | "file_extension": ".py", 94 | "mimetype": "text/x-python", 95 | "name": "python", 96 | "nbconvert_exporter": "python", 97 | "pygments_lexer": "ipython3", 98 | "version": "3.6.5" 99 | } 100 | }, 101 | "nbformat": 4, 102 | "nbformat_minor": 2 103 | } 104 | -------------------------------------------------------------------------------- /Python Projects/moon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonnyhyman/Programming-Classes/f56a9cf90e3b8e4aafad99644f1ed7e87ba14995/Python Projects/moon.jpg -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Programming Classes 2 | 3 | This repo houses all code for classes I've taught at Learn Beyond The Book (learnbeyondthebook.com) 4 | 5 | The license is MIT. 6 | Enjoy and happy learning! 7 | -------------------------------------------------------------------------------- /Technology/W2_BinaryCodes.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Welcome to Week 2!\n", 8 | "\n", 9 | "#### To understand of computers, we are going to learn a little *Python*\n", 10 | "\n", 11 | "![](https://media.giphy.com/media/NAcNfRrU6f2bC/giphy.gif)\n", 12 | "\n", 13 | "\n", 14 | "#### First off, let's say hello to ourselves!" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 4, 20 | "metadata": {}, 21 | "outputs": [ 22 | { 23 | "name": "stdout", 24 | "output_type": "stream", 25 | "text": [ 26 | "Hello!\n" 27 | ] 28 | } 29 | ], 30 | "source": [ 31 | "word = \"Hello!\"\n", 32 | "print(word)" 33 | ] 34 | }, 35 | { 36 | "cell_type": "markdown", 37 | "metadata": {}, 38 | "source": [ 39 | "#### Now, let's figure out what is the \"binary\" of the letter \"J\"?\n", 40 | "- In other words, what is the standard sequence of 0's and 1's that computers use to represent the letter \"J\"?" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 5, 46 | "metadata": {}, 47 | "outputs": [ 48 | { 49 | "name": "stdout", 50 | "output_type": "stream", 51 | "text": [ 52 | "74\n" 53 | ] 54 | } 55 | ], 56 | "source": [ 57 | "letter = \"J\"\n", 58 | "number = ord(letter) # ord gets the \"order\" of the letter\n", 59 | "print(number)" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "#### So, you can see, \"J\" equals 74\n", 67 | "##### ... But what is 74 in binary?" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": 7, 73 | "metadata": {}, 74 | "outputs": [ 75 | { 76 | "name": "stdout", 77 | "output_type": "stream", 78 | "text": [ 79 | "0b1001010\n" 80 | ] 81 | } 82 | ], 83 | "source": [ 84 | "binary = bin(74)\n", 85 | "print(binary)" 86 | ] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": {}, 91 | "source": [ 92 | "# So, \"J\" is 74 is 1001010\n", 93 | "\n", 94 | "![RAD](https://media.giphy.com/media/3o72EYxyS359bvC5Ak/giphy.gif)" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": null, 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [] 103 | } 104 | ], 105 | "metadata": { 106 | "kernelspec": { 107 | "display_name": "Python 3", 108 | "language": "python", 109 | "name": "python3" 110 | }, 111 | "language_info": { 112 | "codemirror_mode": { 113 | "name": "ipython", 114 | "version": 3 115 | }, 116 | "file_extension": ".py", 117 | "mimetype": "text/x-python", 118 | "name": "python", 119 | "nbconvert_exporter": "python", 120 | "pygments_lexer": "ipython3", 121 | "version": "3.6.5" 122 | } 123 | }, 124 | "nbformat": 4, 125 | "nbformat_minor": 2 126 | } 127 | -------------------------------------------------------------------------------- /Technology/W3_CPU.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Before CPU stuff, something cool:" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 31, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "names = [\n", 17 | " \n", 18 | " 'taya',\n", 19 | " 'wyatt',\n", 20 | " 'donovan',\n", 21 | " 'jonny?!',\n", 22 | " \n", 23 | "]" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 32, 29 | "metadata": {}, 30 | "outputs": [ 31 | { 32 | "name": "stdout", 33 | "output_type": "stream", 34 | "text": [ 35 | "taya = [116, 97, 121, 97]\n", 36 | "wyatt = [119, 121, 97, 116, 116]\n", 37 | "donovan = [100, 111, 110, 111, 118, 97, 110]\n", 38 | "jonny?! = [106, 111, 110, 110, 121, 63, 33]\n" 39 | ] 40 | } 41 | ], 42 | "source": [ 43 | "for name in names:\n", 44 | " print(name, '=', [ord(letter) for letter in list(name)])" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": 33, 50 | "metadata": {}, 51 | "outputs": [ 52 | { 53 | "name": "stdout", 54 | "output_type": "stream", 55 | "text": [ 56 | "taya :\n", 57 | " t : 1110100\n", 58 | " a : 1100001\n", 59 | " y : 1111001\n", 60 | " a : 1100001\n", 61 | "wyatt :\n", 62 | " w : 1110111\n", 63 | " y : 1111001\n", 64 | " a : 1100001\n", 65 | " t : 1110100\n", 66 | " t : 1110100\n", 67 | "donovan :\n", 68 | " d : 1100100\n", 69 | " o : 1101111\n", 70 | " n : 1101110\n", 71 | " o : 1101111\n", 72 | " v : 1110110\n", 73 | " a : 1100001\n", 74 | " n : 1101110\n", 75 | "jonny?! :\n", 76 | " j : 1101010\n", 77 | " o : 1101111\n", 78 | " n : 1101110\n", 79 | " n : 1101110\n", 80 | " y : 1111001\n", 81 | " ? : 111111\n", 82 | " ! : 100001\n" 83 | ] 84 | } 85 | ], 86 | "source": [ 87 | "for name in names:\n", 88 | " print(name, ':')\n", 89 | " \n", 90 | " mapping = {letter : \"{0:b}\".format(ord(letter)) \n", 91 | " for letter in list(name)}\n", 92 | " \n", 93 | " for letter in list(name):\n", 94 | " print(' ', letter,':', mapping[letter])" 95 | ] 96 | }, 97 | { 98 | "cell_type": "markdown", 99 | "metadata": {}, 100 | "source": [ 101 | "# COOL BEANS.\n", 102 | "\n", 103 | "#### Now CPU stuff!\n", 104 | "\n", 105 | "\n", 106 | "----\n", 107 | "----\n", 108 | "\n", 109 | "# Quick history of the processor \n", 110 | "## (more on this later)\n", 111 | "\n", 112 | "----\n", 113 | "----\n", 114 | "\n" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": 55, 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "# IGNORE THESE\n", 124 | "import numpy as np\n", 125 | "from numba import njit\n", 126 | "\n", 127 | "# This function adds numbers:\n", 128 | "def add(*args):\n", 129 | " summed = 0\n", 130 | " for a in args:\n", 131 | " summed += a\n", 132 | " return summed" 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": {}, 138 | "source": [ 139 | "# We've made a program to do a very simple CPU operation\n", 140 | "#### ... addition" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": 40, 146 | "metadata": {}, 147 | "outputs": [ 148 | { 149 | "data": { 150 | "text/plain": [ 151 | "2" 152 | ] 153 | }, 154 | "execution_count": 40, 155 | "metadata": {}, 156 | "output_type": "execute_result" 157 | } 158 | ], 159 | "source": [ 160 | "add(1,1)" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": 41, 166 | "metadata": {}, 167 | "outputs": [ 168 | { 169 | "data": { 170 | "text/plain": [ 171 | "10" 172 | ] 173 | }, 174 | "execution_count": 41, 175 | "metadata": {}, 176 | "output_type": "execute_result" 177 | } 178 | ], 179 | "source": [ 180 | "add(1,2,3,4)" 181 | ] 182 | }, 183 | { 184 | "cell_type": "markdown", 185 | "metadata": {}, 186 | "source": [ 187 | "# DUH. But how fast is it?" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": 43, 193 | "metadata": {}, 194 | "outputs": [ 195 | { 196 | "name": "stdout", 197 | "output_type": "stream", 198 | "text": [ 199 | "took 4.00543212890625e-05 seconds\n" 200 | ] 201 | } 202 | ], 203 | "source": [ 204 | "from time import time\n", 205 | "\n", 206 | "start = time()\n", 207 | "add(1,2,4,5,10,100)\n", 208 | "done = time()\n", 209 | "\n", 210 | "print('took', done-start, 'seconds')" 211 | ] 212 | }, 213 | { 214 | "cell_type": "markdown", 215 | "metadata": {}, 216 | "source": [ 217 | "# That's like 0.00004 seconds woah\n", 218 | "\n", 219 | "### But what if we need to add like 1 million numbers?" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": 45, 225 | "metadata": {}, 226 | "outputs": [ 227 | { 228 | "name": "stdout", 229 | "output_type": "stream", 230 | "text": [ 231 | "took 0.06831002235412598 seconds\n" 232 | ] 233 | } 234 | ], 235 | "source": [ 236 | "start = time()\n", 237 | "add(np.random.random(int(1e6)))\n", 238 | "done = time()\n", 239 | "\n", 240 | "print('took', done-start, 'seconds')" 241 | ] 242 | }, 243 | { 244 | "cell_type": "markdown", 245 | "metadata": {}, 246 | "source": [ 247 | "# That's 0.068 seconds, hmmm slower!\n", 248 | "\n", 249 | "### But what if we need to add like 1 trillion numbers, 10 times?" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": 52, 255 | "metadata": {}, 256 | "outputs": [ 257 | { 258 | "name": "stdout", 259 | "output_type": "stream", 260 | "text": [ 261 | "took 2.98760986328125 seconds\n" 262 | ] 263 | } 264 | ], 265 | "source": [ 266 | "p = np.random.random(int(1e8))\n", 267 | "start = time()\n", 268 | "for repeat in range(10):\n", 269 | " add(p)\n", 270 | "done = time()\n", 271 | "\n", 272 | "print('took', done-start, 'seconds')" 273 | ] 274 | }, 275 | { 276 | "cell_type": "markdown", 277 | "metadata": {}, 278 | "source": [ 279 | "# 3 seconds?? TOO SLOW. Let's add in PARALLEL!" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": 53, 285 | "metadata": {}, 286 | "outputs": [], 287 | "source": [ 288 | "# This function adds numbers:\n", 289 | "@njit(parallel=True)\n", 290 | "def padd(args):\n", 291 | " return np.sum(args)" 292 | ] 293 | }, 294 | { 295 | "cell_type": "code", 296 | "execution_count": 54, 297 | "metadata": {}, 298 | "outputs": [ 299 | { 300 | "name": "stdout", 301 | "output_type": "stream", 302 | "text": [ 303 | "took 0.6321461200714111 seconds\n" 304 | ] 305 | } 306 | ], 307 | "source": [ 308 | "p = np.random.random(int(1e8))\n", 309 | "start = time()\n", 310 | "for repeat in range(10):\n", 311 | " padd(p)\n", 312 | "done = time()\n", 313 | "\n", 314 | "print('took', done-start, 'seconds')" 315 | ] 316 | }, 317 | { 318 | "cell_type": "markdown", 319 | "metadata": {}, 320 | "source": [ 321 | "# 0.6 seconds?? Much better!" 322 | ] 323 | }, 324 | { 325 | "cell_type": "markdown", 326 | "metadata": {}, 327 | "source": [] 328 | } 329 | ], 330 | "metadata": { 331 | "kernelspec": { 332 | "display_name": "Python 3", 333 | "language": "python", 334 | "name": "python3" 335 | }, 336 | "language_info": { 337 | "codemirror_mode": { 338 | "name": "ipython", 339 | "version": 3 340 | }, 341 | "file_extension": ".py", 342 | "mimetype": "text/x-python", 343 | "name": "python", 344 | "nbconvert_exporter": "python", 345 | "pygments_lexer": "ipython3", 346 | "version": "3.6.5" 347 | } 348 | }, 349 | "nbformat": 4, 350 | "nbformat_minor": 2 351 | } 352 | -------------------------------------------------------------------------------- /__here__: -------------------------------------------------------------------------------- 1 | cd "/Users/jonny/Dropbox/Jonny's Classes - Transfer and Update Folder/Programming Classes - Repository/Programming-Classes" 2 | --------------------------------------------------------------------------------