Skip to content

Instantly share code, notes, and snippets.

@meli-lewis
Created April 25, 2015 23:01
Show Gist options
  • Save meli-lewis/96262ca78800bb9a25bb to your computer and use it in GitHub Desktop.
Save meli-lewis/96262ca78800bb9a25bb to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {},
"cell_type": "markdown",
"source": "# Solutions for end-of-chapter exercises in [Think Python](http://www.greenteapress.com/thinkpython/)"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "# from __future__ import division\nimport math",
"execution_count": 1,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### Chapter 1 Exercises"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "#### Exercise 1.3"
},
{
"metadata": {
"scrolled": true,
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "help()",
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": "\nWelcome to Python 2.7! This is the online help utility.\n\nIf this is your first time using Python, you should definitely check out\nthe tutorial on the Internet at http://docs.python.org/2.7/tutorial/.\n\nEnter the name of any module, keyword, or topic to get help on writing\nPython programs and using Python modules. To quit this help utility and\nreturn to the interpreter, just type \"quit\".\n\nTo get a list of available modules, keywords, or topics, type \"modules\",\n\"keywords\", or \"topics\". Each module also comes with a one-line summary\nof what it does; to list the modules whose summaries contain a given word\nsuch as \"spam\", type \"modules spam\".\n\nhelp> print\nThe \"print\" statement\n*********************\n\n print_stmt ::= \"print\" ([expression (\",\" expression)* [\",\"]]\n | \">>\" expression [(\",\" expression)+ [\",\"]])\n\n\"print\" evaluates each expression in turn and writes the resulting\nobject to standard output (see below). If an object is not a string,\nit is first converted to a string using the rules for string\nconversions. The (resulting or original) string is then written. A\nspace is written before each object is (converted and) written, unless\nthe output system believes it is positioned at the beginning of a\nline. This is the case (1) when no characters have yet been written\nto standard output, (2) when the last character written to standard\noutput is a whitespace character except \"' '\", or (3) when the last\nwrite operation on standard output was not a \"print\" statement. (In\nsome cases it may be functional to write an empty string to standard\noutput for this reason.)\n\nNote: Objects which act like file objects but which are not the\n built-in file objects often do not properly emulate this aspect of\n the file object's behavior, so it is best not to rely on this.\n\nA \"'\\n'\" character is written at the end, unless the \"print\" statement\nends with a comma. This is the only action if the statement contains\njust the keyword \"print\".\n\nStandard output is defined as the file object named \"stdout\" in the\nbuilt-in module \"sys\". If no such object exists, or if it does not\nhave a \"write()\" method, a \"RuntimeError\" exception is raised.\n\n\"print\" also has an extended form, defined by the second portion of\nthe syntax described above. This form is sometimes referred to as\n\"\"print\" chevron.\" In this form, the first expression after the \">>\"\nmust evaluate to a \"file-like\" object, specifically an object that has\na \"write()\" method as described above. With this extended form, the\nsubsequent expressions are printed to this file object. If the first\nexpression evaluates to \"None\", then \"sys.stdout\" is used as the file\nfor output.\n\nhelp> q\n\nYou are now leaving help and returning to the Python interpreter.\nIf you want to ask for help on a particular object directly from the\ninterpreter, you can type \"help(object)\". Executing \"help('string')\"\nhas the same effect as typing a particular string at the help> prompt.\n"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "#### Exercise 1.4"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "If you run a 10 kilometer race in 43 minutes 30 seconds, what is your average time per mile? What\nis your average speed in miles per hour? (Hint: there are 1.61 kilometers in a mile)."
},
{
"metadata": {},
"cell_type": "markdown",
"source": "$$rate = \\frac{distance}{time}$$\n***\n$$distance:$$\n\n$$\\frac{kilometers}{kilometers/mile} = \\frac{10}{1.61/1} = \\frac{10}{1.61}$$\n***\n$$time:$$\n\n$$\\frac{minutes\\ run}{minutes/mile} = \\frac{43}{60}$$"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "# rate = distance over time\n\n(10/1.61) / (43.5/60)",
"execution_count": 9,
"outputs": [
{
"execution_count": 9,
"output_type": "execute_result",
"data": {
"text/plain": "8.567144998929106"
},
"metadata": {}
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "#average time per mile in hours\n(43.5/60) / (10/1.61)",
"execution_count": 12,
"outputs": [
{
"execution_count": 12,
"output_type": "execute_result",
"data": {
"text/plain": "0.11672500000000001"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "##### Exercise 1.4 Using variables"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "minutes = 43.5\nhours = minutes / 60\nkilometers = 10\nmiles = kilometers / 1.61",
"execution_count": 13,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "miles/hours",
"execution_count": 14,
"outputs": [
{
"execution_count": 14,
"output_type": "execute_result",
"data": {
"text/plain": "8.567144998929106"
},
"metadata": {}
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "hours/miles",
"execution_count": 15,
"outputs": [
{
"execution_count": 15,
"output_type": "execute_result",
"data": {
"text/plain": "0.11672500000000001"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### Chapter 2 Exercises"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "##### Exercise 2.3"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "width = 17\nheight = 12.0\ndelimiter = '.'",
"execution_count": 16,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "width/2",
"execution_count": 17,
"outputs": [
{
"execution_count": 17,
"output_type": "execute_result",
"data": {
"text/plain": "8"
},
"metadata": {}
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "width/2.0",
"execution_count": 18,
"outputs": [
{
"execution_count": 18,
"output_type": "execute_result",
"data": {
"text/plain": "8.5"
},
"metadata": {}
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "height/3",
"execution_count": 19,
"outputs": [
{
"execution_count": 19,
"output_type": "execute_result",
"data": {
"text/plain": "4.0"
},
"metadata": {}
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "1 + 2 * 5",
"execution_count": 20,
"outputs": [
{
"execution_count": 20,
"output_type": "execute_result",
"data": {
"text/plain": "11"
},
"metadata": {}
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "delimiter * 5",
"execution_count": 21,
"outputs": [
{
"execution_count": 21,
"output_type": "execute_result",
"data": {
"text/plain": "'.....'"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "***"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "#### A note on types and division in python: if you're using 2.x, the output of dividing two integers is another, truncated, integer:"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "7/2",
"execution_count": 36,
"outputs": [
{
"execution_count": 36,
"output_type": "execute_result",
"data": {
"text/plain": "3"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "If you want the output to be floating point, make the dividend and/or divisor a floating point as well:"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "7.0/2",
"execution_count": 26,
"outputs": [
{
"execution_count": 26,
"output_type": "execute_result",
"data": {
"text/plain": "3.5"
},
"metadata": {}
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "7/2.0",
"execution_count": 27,
"outputs": [
{
"execution_count": 27,
"output_type": "execute_result",
"data": {
"text/plain": "3.5"
},
"metadata": {}
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "7.0/2.0",
"execution_count": 28,
"outputs": [
{
"execution_count": 28,
"output_type": "execute_result",
"data": {
"text/plain": "3.5"
},
"metadata": {}
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "float(7)/2",
"execution_count": 30,
"outputs": [
{
"execution_count": 30,
"output_type": "execute_result",
"data": {
"text/plain": "3.5"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Note that passing the whole equation to float will just make the output a float:"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "float(7/2)",
"execution_count": 32,
"outputs": [
{
"execution_count": 32,
"output_type": "execute_result",
"data": {
"text/plain": "3.0"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Finally: Python 3 division behaves by default as if it's been passed floats! If you're not yet using it, you can still import that behavior by including the following at the beginning of your document:\n\n```from __future__ import division```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "***"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "##### Exercise 2.4"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "1. The volume of a sphere with radius r is 4/3 * pi * r * ^3. What is the volume of a sphere with radius 5?"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "radius = 5\n\n(4/3.0*math.pi) * radius**3",
"execution_count": 39,
"outputs": [
{
"execution_count": 39,
"output_type": "execute_result",
"data": {
"text/plain": "523.5987755982989"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Downey's hint tells you 392.7 is wrong in case you've forgotten to make a part of 4/3 a float!"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "(4/3*math.pi) * radius**3",
"execution_count": 40,
"outputs": [
{
"execution_count": 40,
"output_type": "execute_result",
"data": {
"text/plain": "392.6990816987241"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "2) Suppose the cover price of a book is \\$24.95 but bookstores get a 40\\% discount. Shipping costs\n$3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "cover_price = 24.95\nbookstore_discount = 0.4\nbookstore_price = cover_price - (cover_price * bookstore_discount)\nfirst_shipping = 3.0\nsubsequent_shipping = 0.75\n\n(60 * bookstore_price) + first_shipping + (subsequent_shipping*59)",
"execution_count": 42,
"outputs": [
{
"execution_count": 42,
"output_type": "execute_result",
"data": {
"text/plain": "945.4499999999999"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "#### A note on rounding and reading documentation\n\nIf that output bothers you too, you can use the built-in Python function [round](https://docs.python.org/2/library/functions.html#round) to clean it up!\n\n```round(number[, ndigits])```\n\nThe above means that when you use ```round```, you need to pass ```number``` and that you have the **[option]** to pass the number of digits you'd like to round to where ```ndigits``` is: as the second argument, following a comma."
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "round(945.4499999999999, 5)",
"execution_count": 45,
"outputs": [
{
"execution_count": 45,
"output_type": "execute_result",
"data": {
"text/plain": "945.45"
},
"metadata": {}
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "3) If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at\ntempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "# set variables\nsecond = 1\nminute = 60 * second\neasy_pace = (8 * minute) + 15\ntempo_pace = (7 * minute) + 12",
"execution_count": 83,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "#calculate run length\nrun_seconds = ((2 * easy_pace) + (3 * tempo_pace))\nrun_minutes = run_seconds / 60",
"execution_count": 84,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "start_hour = 6\nstart_minute = 52\nbreakfast_hour = start_hour + (start_minute + run_minutes) / 60\nbreakfast_minute = (start_minute + run_minutes) % 60",
"execution_count": 87,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "print breakfast_hour, breakfast_minute",
"execution_count": 89,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": "7 30\n"
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "#fancier formatting with string concatenation\nprint str(breakfast_hour) + \":\" + str(int(breakfast_minutes)) + \" am\"",
"execution_count": 90,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": "7:30 am\n"
}
]
}
],
"metadata": {
"kernelspec": {
"name": "python2",
"display_name": "Python 2",
"language": "python"
},
"language_info": {
"mimetype": "text/x-python",
"nbconvert_exporter": "python",
"name": "python",
"pygments_lexer": "ipython2",
"version": "2.7.9",
"file_extension": ".py",
"codemirror_mode": {
"version": 2,
"name": "ipython"
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment