+{"cells":[{"metadata":{},"cell_type":"markdown","source":"**[Python Micro-Course Home Page](https://www.kaggle.com/learn/python)**\n\n---\n"},{"metadata":{},"cell_type":"markdown","source":"These exercises accompany the tutorial on [functions and getting help](https://www.kaggle.com/colinmorris/functions-and-getting-help).\n\nAs before, don't forget to run the setup code below before jumping into question 1."},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"# SETUP. You don't need to worry for now about what this code does or how it works.\nfrom learntools.core import binder; binder.bind(globals())\nfrom learntools.python.ex2 import *\nprint('Setup complete.')","execution_count":1,"outputs":[{"output_type":"stream","text":"Setup complete.\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"# Exercises"},{"metadata":{},"cell_type":"markdown","source":"## 1.\n\nComplete the body of the following function according to its docstring.\n\nHINT: Python has a builtin function `round`"},{"metadata":{"trusted":true},"cell_type":"code","source":"def round_to_two_places(num):\n \"\"\"Return the given number rounded to two decimal places. \n \n >>> round_to_two_places(3.14159)\n 3.14\n \"\"\"\n return round(num,2)\n\nq1.check()","execution_count":2,"outputs":[{"output_type":"display_data","data":{"text/plain":"<IPython.core.display.Javascript object>","application/javascript":"parent.postMessage({\"jupyterEvent\": \"custom.exercise_interaction\", \"data\": {\"outcomeType\": 1, \"valueTowardsCompletion\": 0.5, \"interactionType\": 1, \"learnTutorialId\": 104, \"questionId\": \"1_RoundFunctionProblem\", \"learnToolsVersion\": \"0.2.12\", \"failureMessage\": \"\", \"exceptionClass\": \"\", \"trace\": \"\"}}, \"*\")"},"metadata":{}},{"output_type":"display_data","data":{"text/plain":"Correct","text/markdown":"<span style=\"color:#33cc33\">Correct</span>"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Uncomment the following for a hint\n#q1.hint()\n# Or uncomment the following to peek at the solution\n#q1.solution()","execution_count":3,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 2.\nThe help for `round` says that `ndigits` (the second argument) may be negative.\nWhat do you think will happen when it is? Try some examples in the following cell?\n\nCan you think of a case where this would be useful?"},{"metadata":{"trusted":true},"cell_type":"code","source":"round(123,-2)","execution_count":12,"outputs":[{"output_type":"execute_result","execution_count":12,"data":{"text/plain":"100"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"q2.solution()","execution_count":13,"outputs":[{"output_type":"display_data","data":{"text/plain":"<IPython.core.display.Javascript object>","application/javascript":"parent.postMessage({\"jupyterEvent\": \"custom.exercise_interaction\", \"data\": {\"interactionType\": 3, \"learnTutorialId\": 104, \"questionId\": \"2_RoundNdigitsProblem\", \"learnToolsVersion\": \"0.2.12\", \"valueTowardsCompletion\": 0.0, \"failureMessage\": \"\", \"exceptionClass\": \"\", \"trace\": \"\", \"outcomeType\": 4}}, \"*\")"},"metadata":{}},{"output_type":"display_data","data":{"text/plain":"Solution: As you've seen, `ndigits=-1` rounds to the nearest 10, `ndigits=-2` rounds to the nearest 100 and so on. Where might this be useful? Suppose we're dealing with large numbers:\n\n> The area of Finland is 338,424 km² \n> The area of Greenland is 2,166,086 km²\n\nWe probably don't care whether it's really 338,424, or 338,425, or 338,177. All those digits of accuracy are just distracting. We can chop them off by calling `round()` with `ndigits=-3`:\n\n> The area of Finland is 338,000 km² \n> The area of Greenland is 2,166,000 km²\n\n(We'll talk about how we would get the commas later when we talk about string formatting :))","text/markdown":"<span style=\"color:#33cc99\">Solution:</span> As you've seen, `ndigits=-1` rounds to the nearest 10, `ndigits=-2` rounds to the nearest 100 and so on. Where might this be useful? Suppose we're dealing with large numbers:\n\n> The area of Finland is 338,424 km² \n> The area of Greenland is 2,166,086 km²\n\nWe probably don't care whether it's really 338,424, or 338,425, or 338,177. All those digits of accuracy are just distracting. We can chop them off by calling `round()` with `ndigits=-3`:\n\n> The area of Finland is 338,000 km² \n> The area of Greenland is 2,166,000 km²\n\n(We'll talk about how we would get the commas later when we talk about string formatting :))\n"},"metadata":{}}]},{"metadata":{},"cell_type":"markdown","source":"## 3.\n\nIn a previous programming problem, the candy-sharing friends Alice, Bob and Carol tried to split candies evenly. For the sake of their friendship, any candies left over would be smashed. For example, if they collectively bring home 91 candies, they'll take 30 each and smash 1.\n\nBelow is a simple function that will calculate the number of candies to smash for *any* number of total candies.\n\nModify it so that it optionally takes a second argument representing the number of friends the candies are being split between. If no second argument is provided, it should assume 3 friends, as before.\n\nUpdate the docstring to reflect this new behaviour."},{"metadata":{"trusted":true},"cell_type":"code","source":"def to_smash(total_candies,friends=3):\n \"\"\"Return the number of leftover candies that must be smashed after distributing\n the given number of candies evenly between 3 friends or the number of friends\n explicitly mentioned in the function arguments\n \n >>> to_smash(91)\n 1\n >>> to_smash(102,4)\n 2\n \"\"\"\n return total_candies % friends\n\nq3.check()","execution_count":14,"outputs":[{"output_type":"display_data","data":{"text/plain":"<IPython.core.display.Javascript object>","application/javascript":"parent.postMessage({\"jupyterEvent\": \"custom.exercise_interaction\", \"data\": {\"outcomeType\": 1, \"valueTowardsCompletion\": 0.5, \"interactionType\": 1, \"learnTutorialId\": 104, \"questionId\": \"3_CandySmashingFunctionProblem\", \"learnToolsVersion\": \"0.2.12\", \"failureMessage\": \"\", \"exceptionClass\": \"\", \"trace\": \"\"}}, \"*\")"},"metadata":{}},{"output_type":"display_data","data":{"text/plain":"Correct","text/markdown":"<span style=\"color:#33cc33\">Correct</span>"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"#q3.hint()","execution_count":15,"outputs":[]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"#q3.solution()","execution_count":18,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4.\n\nIt may not be fun, but reading and understanding error messages will be an important part of your Python career.\n\nEach code cell below contains some commented-out buggy code. For each cell...\n\n1. Read the code and predict what you think will happen when it's run.\n2. Then uncomment the code and run it to see what happens. (**Tip**: In the kernel editor, you can highlight several lines and press `ctrl`+`/` to toggle commenting.)\n3. Fix the code (so that it accomplishes its intended purpose without throwing an exception)\n\n<!-- TODO: should this be autochecked? Delta is probably pretty small. -->"},{"metadata":{"trusted":true},"cell_type":"code","source":"round_to_two_places(9.9999)","execution_count":19,"outputs":[{"output_type":"execute_result","execution_count":19,"data":{"text/plain":"10.0"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = -10\ny = 5\n# Which of the two variables above has the smallest absolute value?\nsmallest_abs = min(abs(x), abs(y))\nprint(smallest_abs)","execution_count":23,"outputs":[{"output_type":"stream","text":"5\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"def f(x):\n y = abs(x)\n return y\n\nprint(f(5))","execution_count":24,"outputs":[{"output_type":"stream","text":"5\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"## 5. <span title=\"A bit spicy\" style=\"color: darkgreen \">🌶️</span>\n\nFor this question, we'll be using two functions imported from Python's `time` module.\n\nThe [time](https://docs.python.org/3/library/time.html#time.time) function returns the number of seconds that have passed since the Epoch (aka [Unix time](https://en.wikipedia.org/wiki/Unix_time)). \n\n<!-- We've provided a function called `seconds_since_epoch` which returns the number of seconds that have passed since the Epoch (aka [Unix time](https://en.wikipedia.org/wiki/Unix_time)). -->\n\nTry it out below. Each time you run it, you should get a slightly larger number."},{"metadata":{"trusted":true},"cell_type":"code","source":"# Importing the function 'time' from the module of the same name. \n# (We'll discuss imports in more depth later)\nfrom time import time\nt = time()\nprint(t, \"seconds since the Epoch\")","execution_count":25,"outputs":[{"output_type":"stream","text":"1552569294.1493852 seconds since the Epoch\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"We'll also be using a function called [sleep](https://docs.python.org/3/library/time.html#time.sleep), which makes us wait some number of seconds while it does nothing particular. (Sounds useful, right?)\n\nYou can see it in action by running the cell below:"},{"metadata":{"trusted":true},"cell_type":"code","source":"from time import sleep\nduration = 5\nprint(\"Getting sleepy. See you in\", duration, \"seconds\")\nsleep(duration)\nprint(\"I'm back. What did I miss?\")","execution_count":26,"outputs":[{"output_type":"stream","text":"Getting sleepy. See you in 5 seconds\nI'm back. What did I miss?\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"With the help of these functions, complete the function `time_call` below according to its docstring.\n\n<!-- (The sleep function will be useful for testing here since we have a pretty good idea of what something like `time_call(sleep, 1)` should return.) -->"},{"metadata":{"trusted":true},"cell_type":"code","source":"def time_call(fn, arg):\n \"\"\"Return the amount of time the given function takes (in seconds) when called with the given argument.\n \"\"\"\n t1 = time()\n fn(arg)\n return time()-t1\n\nprint(time_call(sleep,2))","execution_count":32,"outputs":[{"output_type":"stream","text":"2.002103805541992\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"How would you verify that `time_call` is working correctly? Think about it, and then check the answer with the `solution` function below`."},{"metadata":{"trusted":true},"cell_type":"code","source":"#q5.hint()\n#q5.solution()","execution_count":30,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 6. <span title=\"A bit spicy\" style=\"color: darkgreen \">🌶️</span>\n\n*Note: this question depends on a working solution to the previous question.*\n\nComplete the function below according to its docstring."},{"metadata":{"trusted":true},"cell_type":"code","source":"def slowest_call(fn, arg1, arg2, arg3):\n \"\"\"Return the amount of time taken by the slowest of the following function\n calls: fn(arg1), fn(arg2), fn(arg3)\n \"\"\"\n return max(time_call(fn,arg1),time_call(fn,arg2),time_call(fn,arg3))\n \nprint(slowest_call(sleep,1,3,2))","execution_count":36,"outputs":[{"output_type":"stream","text":"3.0031113624572754\n","name":"stdout"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"#q6.hint()","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"#q6.solution()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Keep Going\n\nYou are ready for **[booleans and conditionals](https://www.kaggle.com/colinmorris/booleans-and-conditionals).**\n"},{"metadata":{},"cell_type":"markdown","source":"---\n**[Python Micro-Course Home Page](https://www.kaggle.com/learn/python)**\n\n"}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.5"},"learntools_metadata":{"lesson_index":1,"type":"exercise"}},"nbformat":4,"nbformat_minor":1}
0 commit comments