diff --git a/your-code/challenge-1.ipynb b/your-code/challenge-1.ipynb deleted file mode 100644 index c574eba..0000000 --- a/your-code/challenge-1.ipynb +++ /dev/null @@ -1,248 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# String Operations Lab\n", - "\n", - "**Before your start:**\n", - "\n", - "- Read the README.md file\n", - "- Comment as much as you can and use the resources in the README.md file\n", - "- Happy learning!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import re" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Challenge 1 - Combining Strings\n", - "\n", - "Combining strings is an important skill to acquire. There are multiple ways of combining strings in Python, as well as combining strings with variables. We will explore this in the first challenge. In the cell below, combine the strings in the list and add spaces between the strings (do not add a space after the last string). Insert a period after the last string." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "str_list = ['Durante', 'un', 'tiempo', 'no', 'estuvo', 'segura', 'de', 'si', 'su', 'marido', 'era', 'su', 'marido']\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the cell below, use the list of strings to create a grocery list. Start the list with the string `Grocery list: ` and include a comma and a space between each item except for the last one. Include a period at the end. Only include foods in the list that start with the letter 'b' and ensure all foods are lower case." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "food_list = ['Bananas', 'Chocolate', 'bread', 'diapers', 'Ice Cream', 'Brownie Mix', 'broccoli']\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the cell below, write a function that computes the area of a circle using its radius. Compute the area of the circle and insert the radius and the area between the two strings. Make sure to include spaces between the variable and the strings. \n", - "\n", - "Note: You can use the techniques we have learned so far or use f-strings. F-strings allow us to embed code inside strings. You can read more about f-strings [here](https://www.python.org/dev/peps/pep-0498/)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import math\n", - "\n", - "string1 = \"The area of the circle with radius:\"\n", - "string2 = \"is:\"\n", - "radius = 4.5\n", - "\n", - "def area(x, pi = math.pi):\n", - " # This function takes a radius and returns the area of a circle. We also pass a default value for pi.\n", - " # Input: Float (and default value for pi)\n", - " # Output: Float\n", - " \n", - " # Sample input: 5.0\n", - " # Sample Output: 78.53981633\n", - " \n", - " # Your code here:\n", - " return pi * (x**2)\n", - " \n", - "# Your output string here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Challenge 2 - Splitting Strings\n", - "\n", - "We have first looked at combining strings into one long string. There are times where we need to do the opposite and split the string into smaller components for further analysis. \n", - "\n", - "In the cell below, split the string into a list of strings using the space delimiter. Count the frequency of each word in the string in a dictionary. Strip the periods, line breaks and commas from the text. Make sure to remove empty strings from your dictionary." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "poem = \"\"\"Some say the world will end in fire,\n", - "Some say in ice.\n", - "From what I’ve tasted of desire\n", - "I hold with those who favor fire.\n", - "But if it had to perish twice,\n", - "I think I know enough of hate\n", - "To say that for destruction ice\n", - "Is also great\n", - "And would suffice.\"\"\"\n", - "\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the cell below, find all the words that appear in the text and do not appear in the blacklist. You must parse the string but can choose any data structure you wish for the words that do not appear in the blacklist. Remove all non letter characters and convert all words to lower case." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "blacklist = ['and', 'as', 'an', 'a', 'the', 'in', 'it']\n", - "\n", - "poem = \"\"\"I was angry with my friend; \n", - "I told my wrath, my wrath did end.\n", - "I was angry with my foe: \n", - "I told it not, my wrath did grow. \n", - "\n", - "And I waterd it in fears,\n", - "Night & morning with my tears: \n", - "And I sunned it with smiles,\n", - "And with soft deceitful wiles. \n", - "\n", - "And it grew both day and night. \n", - "Till it bore an apple bright. \n", - "And my foe beheld it shine,\n", - "And he knew that it was mine. \n", - "\n", - "And into my garden stole, \n", - "When the night had veild the pole; \n", - "In the morning glad I see; \n", - "My foe outstretched beneath the tree.\"\"\"\n", - "\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Challenge 3 - Regular Expressions\n", - "\n", - "Sometimes, we would like to perform more complex manipulations of our string. This is where regular expressions come in handy. In the cell below, return all characters that are upper case from the string specified below." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import re\n", - "\n", - "poem = \"\"\"The apparition of these faces in the crowd;\n", - "Petals on a wet, black bough.\"\"\"\n", - "\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the cell below, filter the list provided and return all elements of the list containing a number. To filter the list, use the `re.search` function. Check if the function does not return `None`. You can read more about the `re.search` function [here](https://docs.python.org/3/library/re.html)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n", - "\n", - "# Your code here:\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Bonus Challenge - Regular Expressions II\n", - "\n", - "In the cell below, filter the list provided to keep only strings containing at least one digit and at least one lower case letter. As in the previous question, use the `re.search` function and check that the result is not `None`.\n", - "\n", - "To read more about regular expressions, check out [this link](https://developers.google.com/edu/python/regular-expressions)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n", - "# Your code here:\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.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/your-code/challenge-2.ipynb b/your-code/challenge-2.ipynb deleted file mode 100644 index 6873bd2..0000000 --- a/your-code/challenge-2.ipynb +++ /dev/null @@ -1,326 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Bag of Words Lab\n", - "\n", - "## Introduction\n", - "\n", - "**Bag of words (BoW)** is an important technique in text mining and [information retrieval](https://en.wikipedia.org/wiki/Information_retrieval). BoW uses term-frequency vectors to represent the content of text documents which makes it possible to use mathematics and computer programs to analyze and compare text documents.\n", - "\n", - "BoW contains the following information:\n", - "\n", - "1. A dictionary of all the terms (words) in the text documents. The terms are normalized in terms of the letter case (e.g. `Ironhack` => `ironhack`), tense (e.g. `had` => `have`), singular form (e.g. `students` => `student`), etc.\n", - "1. The number of occurrences of each normalized term in each document.\n", - "\n", - "For example, assume we have three text documents:\n", - "\n", - "DOC 1: **Ironhack is cool.**\n", - "\n", - "DOC 2: **I love Ironhack.**\n", - "\n", - "DOC 3: **I am a student at Ironhack.**\n", - "\n", - "The BoW of the above documents looks like below:\n", - "\n", - "| TERM | DOC 1 | DOC 2 | Doc 3 |\n", - "|---|---|---|---|\n", - "| a | 0 | 0 | 1 |\n", - "| am | 0 | 0 | 1 |\n", - "| at | 0 | 0 | 1 |\n", - "| cool | 1 | 0 | 0 |\n", - "| i | 0 | 1 | 1 |\n", - "| ironhack | 1 | 1 | 1 |\n", - "| is | 1 | 0 | 0 |\n", - "| love | 0 | 1 | 0 |\n", - "| student | 0 | 0 | 1 |\n", - "\n", - "\n", - "The term-frequency array of each document in BoW can be considered a high-dimensional vector. Data scientists use these vectors to represent the content of the documents. For instance, DOC 1 is represented with `[0, 0, 0, 1, 0, 1, 1, 0, 0]`, DOC 2 is represented with `[0, 0, 0, 0, 1, 1, 0, 1, 0]`, and DOC 3 is represented with `[1, 1, 1, 0, 1, 1, 0, 0, 1]`. **Two documents are considered identical if their vector representations have close [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity).**\n", - "\n", - "In real practice there are many additional techniques to improve the text mining accuracy such as using [stop words](https://en.wikipedia.org/wiki/Stop_words) (i.e. neglecting common words such as `a`, `I`, `to` that don't contribute much meaning), synonym list (e.g. consider `New York City` the same as `NYC` and `Big Apple`), and HTML tag removal if the data sources are webpages. In Module 3 you will learn how to use those advanced techniques for [natural language processing](https://en.wikipedia.org/wiki/Natural_language_processing), a component of text mining.\n", - "\n", - "In real text mining projects data analysts use packages such as Scikit-Learn and NLTK, which you will learn in Module 3, to extract BoW from texts. In this exercise, however, we would like you to create BoW manually with Python. This is because by manually creating BoW you can better understand the concept and also practice the Python skills you have learned so far." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The Challenge\n", - "\n", - "We need to create a BoW from a list of documents. The documents (`doc1.txt`, `doc2.txt`, and `doc3.txt`) can be found in the `your-code` directory of this exercise. You will read the content of each document into an array of strings named `corpus`.\n", - "\n", - "*What is a corpus (plural: corpora)? Read the reference in the README file.*\n", - "\n", - "Your challenge is to use Python to generate the BoW of these documents. Your BoW should look like below:\n", - "\n", - "```python\n", - "bag_of_words = ['a', 'am', 'at', 'cool', 'i', 'ironhack', 'is', 'love', 'student']\n", - "\n", - "term_freq = [\n", - " [0, 0, 0, 1, 0, 1, 1, 0, 0],\n", - " [0, 0, 0, 0, 1, 1, 0, 1, 0],\n", - " [1, 1, 1, 0, 1, 1, 0, 0, 1],\n", - "]\n", - "```\n", - "\n", - "Now let's define the `docs` array that contains the paths of `doc1.txt`, `doc2.txt`, and `doc3.txt`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "docs = ['doc1.txt', 'doc2.txt', 'doc3.txt']" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Define an empty array `corpus` that will contain the content strings of the docs. Loop `docs` and read the content of each doc into the `corpus` array." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Write your code here\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Print `corpus`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You expected to see:\n", - "\n", - "```['ironhack is cool', 'i love ironhack', 'i am a student at ironhack']```\n", - "\n", - "But you actually saw:\n", - "\n", - "```['Ironhack is cool.', 'I love Ironhack.', 'I am a student at Ironhack.']```\n", - "\n", - "This is because you haven't done two important steps:\n", - "\n", - "1. Remove punctuation from the strings\n", - "\n", - "1. Convert strings to lowercase\n", - "\n", - "Write your code below to process `corpus` (convert to lower case and remove special characters)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Write your code here" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now define `bag_of_words` as an empty array. It will be used to store the unique terms in `corpus`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Loop through `corpus`. In each loop, do the following:\n", - "\n", - "1. Break the string into an array of terms. \n", - "1. Create a sub-loop to iterate the terms array. \n", - " * In each sub-loop, you'll check if the current term is already contained in `bag_of_words`. If not in `bag_of_words`, append it to the array." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Write your code here\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Print `bag_of_words`. You should see: \n", - "\n", - "```['ironhack', 'is', 'cool', 'i', 'love', 'am', 'a', 'student', 'at']```\n", - "\n", - "If not, fix your code in the previous cell." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now we define an empty array called `term_freq`. Loop `corpus` for a second time. In each loop, create a sub-loop to iterate the terms in `bag_of_words`. Count how many times each term appears in each doc of `corpus`. Append the term-frequency array to `term_freq`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Write your code here\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Print `term_freq`. You should see:\n", - "\n", - "```[[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 0, 1, 1, 1, 1]]```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**If your output is correct, congratulations! You've solved the challenge!**\n", - "\n", - "If not, go back and check for errors in your code." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Bonus Question\n", - "\n", - "Now you want to improve your previous solution by removing the stop words from the corpus. The idea is you only want to add terms that are not in the `stop_words` list to the `bag_of_words` array.\n", - "\n", - "Requirements:\n", - "\n", - "1. Move all your previous codes from `main.ipynb` to the cell below.\n", - "1. Improve your solution by ignoring stop words in `bag_of_words`.\n", - "\n", - "After you're done, your `bag_of_words` should be:\n", - "\n", - "```['ironhack', 'cool', 'love', 'student']```\n", - "\n", - "And your `term_freq` should be:\n", - "\n", - "```[[1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "stop_words = ['all', 'six', 'less', 'being', 'indeed', 'over', 'move', 'anyway', 'fifty', 'four', 'not', 'own', 'through', 'yourselves', 'go', 'where', 'mill', 'only', 'find', 'before', 'one', 'whose', 'system', 'how', 'somewhere', 'with', 'thick', 'show', 'had', 'enough', 'should', 'to', 'must', 'whom', 'seeming', 'under', 'ours', 'has', 'might', 'thereafter', 'latterly', 'do', 'them', 'his', 'around', 'than', 'get', 'very', 'de', 'none', 'cannot', 'every', 'whether', 'they', 'front', 'during', 'thus', 'now', 'him', 'nor', 'name', 'several', 'hereafter', 'always', 'who', 'cry', 'whither', 'this', 'someone', 'either', 'each', 'become', 'thereupon', 'sometime', 'side', 'two', 'therein', 'twelve', 'because', 'often', 'ten', 'our', 'eg', 'some', 'back', 'up', 'namely', 'towards', 'are', 'further', 'beyond', 'ourselves', 'yet', 'out', 'even', 'will', 'what', 'still', 'for', 'bottom', 'mine', 'since', 'please', 'forty', 'per', 'its', 'everything', 'behind', 'un', 'above', 'between', 'it', 'neither', 'seemed', 'ever', 'across', 'she', 'somehow', 'be', 'we', 'full', 'never', 'sixty', 'however', 'here', 'otherwise', 'were', 'whereupon', 'nowhere', 'although', 'found', 'alone', 're', 'along', 'fifteen', 'by', 'both', 'about', 'last', 'would', 'anything', 'via', 'many', 'could', 'thence', 'put', 'against', 'keep', 'etc', 'amount', 'became', 'ltd', 'hence', 'onto', 'or', 'con', 'among', 'already', 'co', 'afterwards', 'formerly', 'within', 'seems', 'into', 'others', 'while', 'whatever', 'except', 'down', 'hers', 'everyone', 'done', 'least', 'another', 'whoever', 'moreover', 'couldnt', 'throughout', 'anyhow', 'yourself', 'three', 'from', 'her', 'few', 'together', 'top', 'there', 'due', 'been', 'next', 'anyone', 'eleven', 'much', 'call', 'therefore', 'interest', 'then', 'thru', 'themselves', 'hundred', 'was', 'sincere', 'empty', 'more', 'himself', 'elsewhere', 'mostly', 'on', 'fire', 'am', 'becoming', 'hereby', 'amongst', 'else', 'part', 'everywhere', 'too', 'herself', 'former', 'those', 'he', 'me', 'myself', 'made', 'twenty', 'these', 'bill', 'cant', 'us', 'until', 'besides', 'nevertheless', 'below', 'anywhere', 'nine', 'can', 'of', 'your', 'toward', 'my', 'something', 'and', 'whereafter', 'whenever', 'give', 'almost', 'wherever', 'is', 'describe', 'beforehand', 'herein', 'an', 'as', 'itself', 'at', 'have', 'in', 'seem', 'whence', 'ie', 'any', 'fill', 'again', 'hasnt', 'inc', 'thereby', 'thin', 'no', 'perhaps', 'latter', 'meanwhile', 'when', 'detail', 'same', 'wherein', 'beside', 'also', 'that', 'other', 'take', 'which', 'becomes', 'you', 'if', 'nobody', 'see', 'though', 'may', 'after', 'upon', 'most', 'hereupon', 'eight', 'but', 'serious', 'nothing', 'such', 'why', 'a', 'off', 'whereby', 'third', 'i', 'whole', 'noone', 'sometimes', 'well', 'amoungst', 'yours', 'their', 'rather', 'without', 'so', 'five', 'the', 'first', 'whereas', 'once']\n", - "\n", - "# Write your code below\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Additional Challenge for the Nerds\n", - "\n", - "We will learn Scikit-Learn in Module 3 which has built in the BoW feature. Try to use Scikit-Learn to generate the BoW for this challenge and check whether the output is the same as yours. You will need to do some googling to find out how to use Scikit-Learn to generate BoW.\n", - "\n", - "**Notes:**\n", - "\n", - "* To install Scikit-Learn, use `pip install sklearn`. \n", - "\n", - "* Scikit-Learn removes stop words by default. You don't need to manually remove stop words.\n", - "\n", - "* Scikit-Learn's output has slightly different format from the output example demonstrated above. It's ok, you don't need to convert the Scikit-Learn output.\n", - "\n", - "The Scikit-Learn output will look like below:\n", - "\n", - "```python\n", - "# BoW:\n", - "{u'love': 5, u'ironhack': 3, u'student': 6, u'is': 4, u'cool': 2, u'am': 0, u'at': 1}\n", - "\n", - "# term_freq:\n", - "[[0 0 1 1 1 0 0]\n", - " [0 0 0 1 0 1 0]\n", - " [1 1 0 1 0 0 1]]\n", - " ```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "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.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/your-code/challenge_1.ipynb b/your-code/challenge_1.ipynb new file mode 100644 index 0000000..c8d6452 --- /dev/null +++ b/your-code/challenge_1.ipynb @@ -0,0 +1,474 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "-4C1RYZfzPvi" + }, + "source": [ + "# String Operations Lab\n", + "\n", + "**Before your start:**\n", + "\n", + "- Read the README.md file\n", + "- Comment as much as you can and use the resources in the README.md file\n", + "- Happy learning!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "iFHGK_ktzPvl" + }, + "outputs": [], + "source": [ + "import re" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "_zZ9ovXKzPvn" + }, + "source": [ + "# Challenge 1 - Combining Strings\n", + "\n", + "Combining strings is an important skill to acquire. There are multiple ways of combining strings in Python, as well as combining strings with variables. We will explore this in the first challenge. In the cell below, combine the strings in the list and add spaces between the strings (do not add a space after the last string). Insert a period after the last string." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "i17JpleIzPvo", + "outputId": "1a0b0681-4a73-4ffe-9747-ab3aa44ec23d" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Durante un tiempo no estuvo segura de si su marido era su marido.\n" + ] + } + ], + "source": [ + "str_list = ['Durante', 'un', 'tiempo', 'no', 'estuvo', 'segura', 'de', 'si', 'su', 'marido', 'era', 'su', 'marido']\n", + "# Your code here:\n", + "result_1 = \" \".join(str_list) + '.'\n", + "print(result_1)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "R1ZH-McpzPvp" + }, + "source": [ + "In the cell below, use the list of strings to create a grocery list. Start the list with the string `Grocery list: ` and include a comma and a space between each item except for the last one. Include a period at the end. Only include foods in the list that start with the letter 'b' and ensure all foods are lower case." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "Az1knCubzPvq", + "outputId": "b40127ae-1b26-4fe0-9ba5-0d5d606d1e22" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Grocery list:bread, broccoli.\n" + ] + } + ], + "source": [ + "food_list = ['Bananas', 'Chocolate', 'bread', 'diapers', 'Ice Cream', 'Brownie Mix', 'broccoli']\n", + "# Your code here:\n", + "grocery_list = \"Grocery list:\" + \", \".join([i for i in food_list if i.startswith('b')]) + \".\"\n", + "print(grocery_list)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ntVtVOvAzPvr" + }, + "source": [ + "In the cell below, write a function that computes the area of a circle using its radius. Compute the area of the circle and insert the radius and the area between the two strings. Make sure to include spaces between the variable and the strings. \n", + "\n", + "Note: You can use the techniques we have learned so far or use f-strings. F-strings allow us to embed code inside strings. You can read more about f-strings [here](https://www.python.org/dev/peps/pep-0498/)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "zVr8iPOpzPvs", + "outputId": "f82b9b49-3386-45f4-d74d-245f31a87666" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "The area of the circle with radius:4.5 is: 63.61725123519331\n" + ] + } + ], + "source": [ + "import math\n", + "\n", + "string1 = \"The area of the circle with radius:\"\n", + "string2 = \"is:\"\n", + "radius = 4.5\n", + "\n", + "def area(x, pi = math.pi):\n", + " # This function takes a radius and returns the area of a circle. We also pass a default value for pi.\n", + " # Input: Float (and default value for pi)\n", + " # Output: Float\n", + " \n", + " # Sample input: 5.0\n", + " # Sample Output: 78.53981633\n", + " \n", + " # Your code here:\n", + " return pi * (x**2)\n", + " \n", + "# Your output string here:\n", + "print(f\"{string1}{radius} {string2} {area(radius)}\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ok6gTDiqzPvt" + }, + "source": [ + "# Challenge 2 - Splitting Strings\n", + "\n", + "We have first looked at combining strings into one long string. There are times where we need to do the opposite and split the string into smaller components for further analysis. \n", + "\n", + "In the cell below, split the string into a list of strings using the space delimiter. Count the frequency of each word in the string in a dictionary. Strip the periods, line breaks and commas from the text. Make sure to remove empty strings from your dictionary." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "do54Ox5yzPvv", + "outputId": "031d076d-7091-40fd-aa7b-6647a28c0c61" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "{'Some': 2, 'say': 3, 'the': 1, 'world': 1, 'will': 1, 'end': 1, 'in': 2, 'fire': 2, 'ice': 2, 'From': 1, 'what': 1, 'I’ve': 1, 'tasted': 1, 'of': 2, 'desire': 1, 'I': 3, 'hold': 1, 'with': 1, 'those': 1, 'who': 1, 'favor': 1, 'But': 1, 'if': 1, 'it': 1, 'had': 1, 'to': 1, 'perish': 1, 'twice': 1, 'think': 1, 'know': 1, 'enough': 1, 'hate': 1, 'To': 1, 'that': 1, 'for': 1, 'destruction': 1, 'Is': 1, 'also': 1, 'great': 1, 'And': 1, 'would': 1, 'suffice': 1}\n" + ] + } + ], + "source": [ + "poem = \"\"\"Some say the world will end in fire,\n", + "Some say in ice.\n", + "From what I’ve tasted of desire\n", + "I hold with those who favor fire.\n", + "But if it had to perish twice,\n", + "I think I know enough of hate\n", + "To say that for destruction ice\n", + "Is also great\n", + "And would suffice.\"\"\"\n", + "\n", + "# Your code here:\n", + "# Splitting the poem string into individual words and storing into temp1 variable\n", + "temp1 = poem.split()\n", + "# STripping the commas and fullstop from the words and storing all the words in the temp2 variable\n", + "temp2 = []\n", + "for i in temp1:\n", + " if i.endswith('.'):\n", + " temp2.append(i.strip('.'))\n", + " elif i.endswith(','):\n", + " temp2.append(i.strip(','))\n", + " else:\n", + " temp2.append(i)\n", + "\n", + "# Counting the frequency of each and every word and storing in the frequency dictionary\n", + "freq_dict = {}\n", + "for i in temp2:\n", + " # Adding 1 to the count of a new word and adding 1 to the previous count of a word if that word is encountered again\n", + " freq_dict[i] = freq_dict.get(i, 0) + 1\n", + "\n", + "# Removing an empty string\n", + "for key in freq_dict:\n", + " if len(key) == 0:\n", + " freq_dict.pop(key)\n", + "\n", + "print(freq_dict)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "iBMPY02nzPvz" + }, + "source": [ + "In the cell below, find all the words that appear in the text and do not appear in the blacklist. You must parse the string but can choose any data structure you wish for the words that do not appear in the blacklist. Remove all non letter characters and convert all words to lower case." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "a4zheRiCzPv7", + "outputId": "0cf4b483-68ca-4041-97f1-b1967deba0c4" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "['i', 'was', 'angry', 'with', 'my', 'friend', 'i', 'told', 'my', 'wrath', 'my', 'wrath', 'did', 'end', 'i', 'was', 'angry', 'with', 'my', 'foe', 'i', 'told', 'not', 'my', 'wrath', 'did', 'grow', 'i', 'waterd', 'fears', 'night', 'morning', 'with', 'my', 'tears', 'i', 'sunned', 'with', 'smiles', 'with', 'soft', 'deceitful', 'wiles', 'grew', 'both', 'day', 'night', 'till', 'bore', 'apple', 'bright', 'my', 'foe', 'beheld', 'shine', 'he', 'knew', 'that', 'was', 'mine', 'into', 'my', 'garden', 'stole', 'when', 'night', 'had', 'veild', 'pole', 'morning', 'glad', 'i', 'see', 'my', 'foe', 'outstretched', 'beneath', 'tree']\n" + ] + } + ], + "source": [ + "blacklist = ['and', 'as', 'an', 'a', 'the', 'in', 'it']\n", + "\n", + "poem = \"\"\"I was angry with my friend; \n", + "I told my wrath, my wrath did end.\n", + "I was angry with my foe: \n", + "I told it not, my wrath did grow. \n", + "\n", + "And I waterd it in fears,\n", + "Night & morning with my tears: \n", + "And I sunned it with smiles,\n", + "And with soft deceitful wiles. \n", + "\n", + "And it grew both day and night. \n", + "Till it bore an apple bright. \n", + "And my foe beheld it shine,\n", + "And he knew that it was mine. \n", + "\n", + "And into my garden stole, \n", + "When the night had veild the pole; \n", + "In the morning glad I see; \n", + "My foe outstretched beneath the tree.\"\"\"\n", + "\n", + "# Your code here:\n", + "# Converting all the words into lower case\n", + "poem = poem.lower()\n", + "\n", + "# Splitting the poem string into individual words and storing into temp1 variable\n", + "temp1 = poem.split()\n", + "\n", + "# STripping the commas, colon, semi-colon, fullstop and removing non-letter characters from the words and storing all the words in the temp2 variable\n", + "temp2 = []\n", + "for i in temp1:\n", + " if i.endswith('.'):\n", + " temp2.append(i.strip('.'))\n", + " elif i.endswith(','):\n", + " temp2.append(i.strip(','))\n", + " elif i.endswith(':'):\n", + " temp2.append(i.strip(':'))\n", + " elif i.endswith(';'):\n", + " temp2.append(i.strip(';'))\n", + " elif not i.isalpha():\n", + " pass\n", + " else:\n", + " temp2.append(i)\n", + "\n", + "# Now filtering the words that are not in blacklist\n", + "result = [i for i in temp2 if i not in blacklist]\n", + "print(result)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "zsk3RUHzzPwE" + }, + "source": [ + "# Challenge 3 - Regular Expressions\n", + "\n", + "Sometimes, we would like to perform more complex manipulations of our string. This is where regular expressions come in handy. In the cell below, return all characters that are upper case from the string specified below." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "iZuLkOJQzPwG", + "outputId": "cbf6ed4a-8967-417e-b45a-faea8ddbb380" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "['T', 'P']" + ] + }, + "metadata": {}, + "execution_count": 46 + } + ], + "source": [ + "import re\n", + "\n", + "poem = \"\"\"The apparition of these faces in the crowd;\n", + "Petals on a wet, black bough.\"\"\"\n", + "\n", + "# Your code here:\n", + "# Forming the regular expression to extract all the upper case characters\n", + "h = re.compile('[A-Z]')\n", + "# Finding all the characters that satusfies our regular expression\n", + "h.findall(poem)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "jXyT5m_2zPwH" + }, + "source": [ + "In the cell below, filter the list provided and return all elements of the list containing a number. To filter the list, use the `re.search` function. Check if the function does not return `None`. You can read more about the `re.search` function [here](https://docs.python.org/3/library/re.html)." + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "Eh3uwo8IzPwI", + "outputId": "c3a7e818-edf4-4d43-a8e6-63a639c67173" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "123abc\n", + "abc123\n", + "JohnSmith1\n", + "ABBY4\n" + ] + } + ], + "source": [ + "data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n", + "\n", + "# Your code here:\n", + "for word in data:\n", + " match = re.search(r'\\d+', word)\n", + " if match is None:\n", + " pass\n", + " else:\n", + " print(word)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "F2ATvdlczPwJ" + }, + "source": [ + "# Bonus Challenge - Regular Expressions II\n", + "\n", + "In the cell below, filter the list provided to keep only strings containing at least one digit and at least one lower case letter. As in the previous question, use the `re.search` function and check that the result is not `None`.\n", + "\n", + "To read more about regular expressions, check out [this link](https://developers.google.com/edu/python/regular-expressions)." + ] + }, + { + "cell_type": "code", + "execution_count": 88, + "metadata": { + "id": "2Flf0UENzPwX", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "9150aa99-bdc9-4bbb-bd6e-a33813150b16" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "123abc\n", + "abc123\n", + "JohnSmith1\n" + ] + } + ], + "source": [ + "data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n", + "# Your code here:\n", + "for word in data:\n", + " match = re.search('(?=.*?[0-9])(?=.*?[a-z])', word)\n", + " if match is None:\n", + " pass\n", + " else:\n", + " print(word)" + ] + }, + { + "cell_type": "code", + "source": [ + "" + ], + "metadata": { + "id": "FdVp-YwjwYkD" + }, + "execution_count": 63, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.9.7" + }, + "colab": { + "name": "challenge-1.ipynb", + "provenance": [], + "collapsed_sections": [] + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file