{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "pattWp_yvpLL" }, "source": [ "# Introduction to Python \n", "\n", "### Function Exercises (Solutions) " ] }, { "cell_type": "markdown", "metadata": { "id": "py4kgaMh7YSn" }, "source": [ "#### 1) Write a function that takes an integer minutes and converts it to seconds. (EASY)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "id": "W94FceP87YSp" }, "outputs": [], "source": [ "def minutes_to_seconds(minutes):\n", " secs = minutes*60\n", " return secs" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "5JF_rv0YLcq_", "outputId": "1177dcfd-4825-4247-db81-c95599fdc513" }, "outputs": [ { "data": { "text/plain": [ "900" ] }, "execution_count": 3, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "minutes_to_seconds(15)" ] }, { "cell_type": "markdown", "metadata": { "id": "V8Iygkok7YSv" }, "source": [ "#### 2) Create a function that converts a date formatted as MM/DD/YYYY to YYYYDDMM. The input is a string! \n", "\n", "(do not use datetime module)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "id": "6upXFRJO7YSw" }, "outputs": [], "source": [ "def date_formatting(string_date):\n", " date_list = string_date.split('/')\n", " date_list.reverse()\n", " output = ''.join(date_list)\n", " return output" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 36 }, "id": "sNFxLihj9IeO", "outputId": "97cd9348-2ed5-4da9-afdd-b0be138e34ff" }, "outputs": [ { "data": { "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" }, "text/plain": [ "'20202209'" ] }, "execution_count": 5, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "date_formatting('09/22/2020')" ] }, { "cell_type": "markdown", "metadata": { "id": "pQvZBRBl7YS4" }, "source": [ "#### 3) A typical car can hold four passengers and one driver, allowing five people to travel around. Given n number of people, `return` how many cars are needed to seat everyone comfortably." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "id": "miOwYnQq7YS7" }, "outputs": [], "source": [ "def car(numeric):\n", " if numeric % 5 == 0:\n", " return numeric/5\n", " else:\n", " return numeric//5 + 1\n", " #return int(numeric/5) + 1" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "id": "LEnhSlcALhd6", "outputId": "82563cf6-7fce-4f26-f725-b7494b64d7b4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "5\n" ] } ], "source": [ "print(car(19))\n", "print(car(21))" ] }, { "cell_type": "markdown", "metadata": { "id": "ZO_CEExZ7YTD" }, "source": [ "#### 4) Create a function that replaces all the vowels in a string with the character '#'." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "id": "jOTdsBhB7YTF" }, "outputs": [], "source": [ "def hashtag_vowels(a_string):\n", " vowels = 'aieou' + 'aieou'.upper()\n", " for i in vowels:\n", " a_string = a_string.replace(i,'#')\n", " return a_string" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 36 }, "id": "dV7I4nN0BbbY", "outputId": "a663366f-51f3-4a66-f22c-f5da18b9bddf" }, "outputs": [ { "data": { "text/plain": [ "\"#'v# h#d th# t#m# #f my l#f#\"" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hashtag_vowels(\"I've had the time of my life\")" ] }, { "cell_type": "markdown", "metadata": { "id": "FYD3iuoF7YTL" }, "source": [ "#### 5) Write a function that inverts the keys and values of a dictionary." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "id": "KPYSn3Wo7YTM" }, "outputs": [], "source": [ "def invert_keys_values(dictionary):\n", " dictionary2 = dict()\n", " for i,j in dictionary.items():\n", " dictionary2[j] = i \n", " return dictionary2" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "d3yRFUD6Lz-Q", "outputId": "ca5bfe40-129c-40e6-88ec-d2efe390f063" }, "outputs": [ { "data": { "text/plain": [ "{1: 'a', 2: 'b'}" ] }, "execution_count": 14, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "invert_keys_values({'a':1,'b':2})" ] }, { "cell_type": "markdown", "metadata": { "id": "thED9zJq7YTR" }, "source": [ "#### 6) Create a function that takes a list of strings and return a list, sorted from shortest to longest." ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "id": "sQVQHJpx7YTS" }, "outputs": [], "source": [ "#1 Version\n", "\n", "def len_string(list_string):\n", " dict_strings = dict()\n", " a_list = []\n", "\n", " # creating a dictionary with the word:len(word)\n", " for i in list_string:\n", " dict_strings[i] = len(i)\n", " \n", " # sorting it\n", " for j in sorted(dict_strings.items(), key = lambda x:x[1]):\n", " a_list.append(j[0])\n", "\n", " return a_list" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "2jCBMRW1L506", "outputId": "7fec92c9-8dee-4531-8e11-9c8e4215938d" }, "outputs": [ { "data": { "text/plain": [ "['1', '333', '666666', '999999999']" ] }, "execution_count": 16, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "len_string(['1','999999999','666666','333'])" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "id": "UZ9rwtcaEOjS" }, "outputs": [], "source": [ "#2 Version\n", "\n", "def len_string2(list_string):\n", " list_string.sort(key=lambda x:len(x))\n", " return list_string" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "jpT112ahMDwI", "outputId": "4e878fc4-8216-4095-cae1-51414968636d" }, "outputs": [ { "data": { "text/plain": [ "['1', '333', '666666', '999999999']" ] }, "execution_count": 19, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "len_string2(['1','999999999','666666','333'])" ] }, { "cell_type": "markdown", "metadata": { "id": "Dk9XB17L7YTY" }, "source": [ "#### 7) Create a function that receives two list as parameters, and returns True if the first list is a subset of the second, or False otherwise. Do not use sets." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "id": "PkGrla307YTZ" }, "outputs": [], "source": [ "def subset_list(first_list,second_list):\n", " a = []\n", " second_list_copy = second_list.copy()\n", " for i in first_list:\n", " if i in second_list:\n", " a.append(i)\n", " try:\n", " second_list_copy.remove(i)\n", " except:\n", " return False \n", " print(a) \n", " if a == first_list:\n", " return True\n", " else:\n", " return False" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "id": "9vLAqeemcbjV", "outputId": "c23b4fcf-60e2-4ea9-ec9c-0da19c874dc3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n" ] }, { "data": { "text/plain": [ "True" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "subset_list([1,2,3], [1,2,3,4,5,6])" ] }, { "cell_type": "markdown", "metadata": { "id": "ou_5mpxh7YTe" }, "source": [ "#### 8) Create a function that takes an integer and returns the factorial of that integer. That is, the integer multiplied by all positive lower integers." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "id": "K3TyaPMh7YTf" }, "outputs": [], "source": [ "def fatorial(integer):\n", " a = 1\n", " for i in range(1,integer+1):\n", " a *= i #a = a*1\n", " return a" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "Cq5NK5x8vQPZ", "outputId": "b51c1cbe-b693-4929-f65a-83f083ea9858" }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 21, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "fatorial(0)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "3j7TFZzRMLcq", "outputId": "004ca85d-0866-4e9f-fa8a-719039932d26" }, "outputs": [ { "data": { "text/plain": [ "120" ] }, "execution_count": 22, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "fatorial(5)" ] }, { "cell_type": "markdown", "metadata": { "id": "32yVTekk7YTk" }, "source": [ "#### 9) Create a function that takes a number as an argument and returns how many times it is multiple of 3." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "id": "uqpmby097YTl" }, "outputs": [], "source": [ "def multiple_3(integer):\n", " count_times = 0\n", " while integer % 3 == 0:\n", " integer /= 3 \n", " count_times += 1\n", " return count_times" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "64NThv05MN3M", "outputId": "0d90d88e-b054-457e-f42c-a8089a6e13be" }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 24, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "multiple_3(3*3*3*3*4)" ] }, { "cell_type": "markdown", "metadata": { "id": "h66ZpY8h7YTq" }, "source": [ "#### 10) Create a function that sorts a list and removes all duplicate items from it. (Don't use 'set')" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "id": "tUin392n7YTr" }, "outputs": [], "source": [ "def sort_and_remove_duplicate(a_list):\n", " new_list = []\n", " for i in a_list:\n", " if str(i) not in new_list:\n", " new_list.append(str(i))\n", " new_list.sort()\n", " return new_list" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "BQ0DieJQx1vE", "outputId": "db8124ec-531f-43d7-d7d3-8cfc58ed77f3" }, "outputs": [ { "data": { "text/plain": [ "['1', '2', '3', '6', '9']" ] }, "execution_count": 26, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "sort_and_remove_duplicate([9]*3+[6]*2+[1,2,3]*3)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "gJBuOZMHx-rX", "outputId": "6b601f12-1050-49f6-e03f-7ccc4c8a3fdc" }, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 27, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "sort_and_remove_duplicate(['a']*10+['b']*4+['c']*3)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ck9o6OOEvpLM" }, "source": [ "#### 11) Create a function that checks if the number is even or odd" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "GXwabN6u-REU" }, "outputs": [], "source": [ "def even_odd(num):\n", " if num %2==0:\n", " return 'is_even'\n", " else:\n", " return 'is_odd'" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "yzGK5dYvvpLP" }, "source": [ "#### 12) Create a function that receives a list, an element, a position and add the element in the given position in the list. This list is going to be the output of the function. " ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "colab": {}, "colab_type": "code", "id": "heHNjDZi-awh" }, "outputs": [], "source": [ "def add_element_list(a_list, element, position):\n", " a_list.insert(position,element)\n", " return a_list" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "-egK1A8ovpLQ" }, "source": [ "#### 13) Create a function that receives multiple parameters and returns a list with all the parameters" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "E8Thq2UU-3QW" }, "outputs": [], "source": [ "def multiple_parameters(*args):\n", " return list(args)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Nn6XfMZbvpLQ" }, "source": [ "#### 14) Given a string, create a function that finds every word that contains a letter given as a parameter" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "colab_type": "code", "id": "VQgCHYadNZ95", "outputId": "92275d25-44df-4848-b24b-6523bcbaecb3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n" ] } ], "source": [ "import string\n", "\n", "print(string.punctuation)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "colab": {}, "colab_type": "code", "id": "3xVz42jcC3f5" }, "outputs": [], "source": [ "def find_letter(text,letter):\n", " \n", " # storing every word in a list of strings\n", " words = []\n", " for w in text.split():\n", " words.append(w.lower().strip(string.punctuation))\n", " \n", " # storing only the words that contains the letter\n", " chosen_words = []\n", " for w in words:\n", " if letter in w:\n", " chosen_words.append(w)\n", "\n", " return chosen_words" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "colab": {}, "colab_type": "code", "id": "w8HOvR2QNgTv" }, "outputs": [], "source": [ "a = 'A text with the letters a, b, c, d, and e'\n", "b = 'e'" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "pBWWjKb4NlJO", "outputId": "d121ef70-a035-43df-cb3d-d521ebc6eaab" }, "outputs": [ { "data": { "text/plain": [ "['text', 'the', 'letters', 'e']" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "find_letter(a,b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 15) [Project Euler problem #17](https://projecteuler.net/index.php?section=problems&id=17) \n", "\n", "If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.\n", "If all the numbers from 1 to 1000 (one thousand, inclusive) were written out in words, how many letters would be used?\n", "\n", "NOTE: Do not count spaces or hyphens. For example, the number 342 (three hundred and forty-two) contains 23 letters and the number 115 (one hundred and fifteen) contains 20 letters. The use of \"and\" when writing out numbers is in compliance with British usage.\n", "\n", "Hint: Create a function (or a set of functions) that receives an integer and returns it in \"written_form\".\n", "\n", "Example: \n", "\n", " print(written_number(234)) \n", " > 'two hundred and thirty-four' " ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "colab": {}, "colab_type": "code", "id": "hVXD-3eBWffu" }, "outputs": [], "source": [ "def written_number(n):\n", " digits_written_nums = {0: '',1: 'one',2: 'two',3: 'three', 4: 'four', 5: 'five', 6: 'six',7: 'seven',8: 'eight',9: 'nine',\n", " 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen',18: 'eighteen', 19: 'nineteen',\n", " 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'}\n", " \n", " # empty string\n", " written_num = ''\n", "\n", " # decomposing the number!\n", "\n", " # hundred\n", " if n >= 100:\n", " written_num = written_num + digits_written_nums[n//100]\n", " written_num = written_num + \" hundred \"\n", " # here n is replaced to rest of n/100\n", " n = n%100\n", " if n is not 0:\n", " written_num = written_num + 'and '\n", "\n", " # hundred + >20\n", " if n > 20:\n", " written_num = written_num + digits_written_nums[n-n%10]\n", " written_num = written_num + ' '\n", " written_num = written_num + digits_written_nums[n%10]\n", "\n", " # hundred + <20\n", " # elif is required because if n>20, this block is not necessa\n", " elif n <= 20:\n", " written_num += digits_written_nums[n]\n", "\n", " # Return the number as string\n", " return written_num" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "colab": {}, "colab_type": "code", "id": "rEfO7KI_DXWl" }, "outputs": [], "source": [ "def count_characters(a_string):\n", " a_string = a_string.replace(' ','')\n", " return(len(a_string))" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "ieUiUyUzDaC1", "outputId": "fe7d528e-5a36-4948-836e-e8fec6f9bc7a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "21113\n" ] } ], "source": [ "total = 0\n", "for num in range(1,1000):\n", " total += count_characters(written_number(num))\n", "print(total)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 16) [Project Euler problem #19](https://projecteuler.net/index.php?section=problems&id=1) \n", "\n", "\"Counting Sundays\"\n", "- 1 Jan 1900 was a Monday. \n", "- Thirty days has September,\n", "April, June and November.\n", "- All the rest have thirty-one,\n", "- Saving February alone, which has twenty-eight, rain or shine.\n", "- And on leap years, twenty-nine.\n", "- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.\n", "\n", "\n", "How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?\n", "\n", "Hint: Use OrderedDict" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "from collections import OrderedDict" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "dict_days = OrderedDict({ \"January\": 31, \n", " \"February\" : 28, \n", " \"March\" : 31, \n", " \"April\" : 30, \n", " \"May\" : 31, \n", " \"June\" : 30, \n", " \"July\" : 31, \n", " \"August\" : 31, \n", " \"September\" : 30, \n", " \"October\" : 31, \n", " \"November\" : 30, \n", " \"December\" : 31})" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "day = 1\n", "sundays = 0\n", "for i in range(1900,2001):\n", " for j in dict_days.keys():\n", " if int(str(i)[2:]) % 4 == 0 and j == 'February':\n", " day += 29\n", " if i > 1900 and day % 7 == 0:\n", " sundays += 1\n", " else:\n", " day += dict_days[j]\n", " if i > 1900 and day % 7 == 0:\n", " sundays += 1" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "171" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sundays" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "Gabarito 1st_Assignment.ipynb", "provenance": [] }, "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.8.5" } }, "nbformat": 4, "nbformat_minor": 4 }