{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**a)** Take a few minutes to browse the modules in the [Python module index](https://docs.python.org/3/py-modindex.html)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**b)** Import the module `datetime`, a module that provides functionality for working with dates. We will now use it to calculate your age in days, hours and seconds repsectively.\n", "\n", "Write a function that accepts a birth date of a person:\n", "\n", "`> calculate_age(1999, 1, 2, hour=12, minute=2, second=33)`\n", "```\n", "You are 7263 days old\n", "You are 174313 hours old\n", "You are 627527127 seconds old\n", "```\n", "\n", "\n", "Year, month and date is required, the other values are optional. The default values of hour, minute and second should be 0.\n", "\n", "The function should print the following:\n", "\n", "- How many days is the person?\n", "- How many hours is the person?\n", "- How many seconds is the person?\n", "\n", "The `datetime` module will provide you with the number of days and seconds. You will need to calculate the number of hours on your own.\n", "\n", "**Hints:**\n", "- Use the [`datetime Object`](https://docs.python.org/3/library/datetime.html#datetime-objects) to solve the exercise.\n", "\n", "- Find out how to make a `datetime` object representing the current time.\n", "\n", "- Find out how to make a `datetime` object representing a given date and time (the birth date). \n", "\n", "- Look at the supported operations for this type to find how you can get the difference between two objects of type `datetime`.\n", "\n", "- You will get difference represented as an object (a [`timedelta`](https://docs.python.org/3/library/datetime.html#timedelta-objects)).\n", "\n", "- Use `.days` and `.total_seconds()` to get the number of days and seconds." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**c)** Test your functions by giving it different input and make sure that they give the expected output." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Bonus exercises" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**d)** Go back to the previous IMDB exercise, where you defined the `pick_movie()` function.\n", "\n", "Use the module `random` to make the movie picker less predictable: instead of always returning the first matching movie from the file, return a randomly picked movie (which still matches the user's criteria)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "-----\n", "



\n", "
\n", "
\n", "

Proposed solution

\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Proposed solution for b)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import datetime\n", "\n", "def calculate_age(year, month, day, hour=0, minute=0, second=0):\n", " \"\"\" Calculate the number of days, hours and seconds that have passed since a given date \"\"\"\n", " # create a date object for current time\n", " now = datetime.datetime.now()\n", " # create a date object for the giventime\n", " born = datetime.datetime(year, month, day, hour, minute, second)\n", " # compare them\n", " diff = now - born\n", " # get the number of days that have passed\n", " days = diff.days\n", " # get the number of seconds\n", " tot_seconds = int(diff.total_seconds())\n", " # convert into hours using floor division\n", " hours = tot_seconds // 3600\n", " print('You are ' + str(days) + ' days old')\n", " print('You are ' + str(hours) + ' hours old')\n", " print('You are ' + str(tot_seconds) + ' seconds old')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "You are 12650 days old\n", "You are 303615 hours old\n", "You are 1093014139 seconds old\n" ] } ], "source": [ "calculate_age(1984, 3, 19)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Proposed solution for the bonus exercise" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "import random\n", "\n", "imdb = \"../../downloads/250.imdb\"\n", "\n", "def pick_movie_b_ii(year=None, genre=None, rating_min=None, rating_max=None):\n", " # read all lines and keep them in memory\n", " lines = open(imdb).readlines()\n", " # use random to shuffle the lines (put them in random order)\n", " random.shuffle(lines)\n", " # now go through the lines and return the first one that fits\n", " for line in lines:\n", " if line.startswith('#'):\n", " continue\n", " fields = line.split('|')\n", " # Remeber to type cast to float\n", " rating = float(fields[1].strip())\n", " title = fields[-1].strip()\n", " m_year = fields[2].strip()\n", " genres = fields[-2].strip().split(',')\n", " # Go through criterias\n", " ok_year = not year or m_year == year\n", " ok_genre = not genre or genre in genres\n", " ok_min = not rating_min or rating_min <= rating\n", " ok_max = not rating_max or rating_max >= rating\n", " if ok_year and ok_genre and ok_min and ok_max:\n", " # All criterias ok, print the movie and break the loop\n", " print(title)\n", " break\n" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A Beautiful Mind\n" ] } ], "source": [ "pick_movie_b_ii(year=\"2001\")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Spirited Away\n" ] } ], "source": [ "pick_movie_b_ii(year=\"2001\")" ] } ], "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" } }, "nbformat": 4, "nbformat_minor": 2 }