Skip to content

[lab-string-operations] Matheus Freire #216

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
338 changes: 338 additions & 0 deletions your-code/Strings_challenge-1_Matheus_Freire (1).ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,338 @@
{
"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": 1,
"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) . ( pay attention) Insert a period after the last string."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"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",
"\n",
"\n",
"combined_str = ' '.join(str_list[:-1]) + '.' + str_list[-1]\n",
"\n",
"print(combined_str)"
]
},
{
"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": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Grocery list: bananas, bread, brownie mix, broccoli.\n"
]
}
],
"source": [
"food_list = ['Bananas', 'Chocolate', 'bread', 'diapers', 'Ice Cream', 'Brownie Mix', 'broccoli']\n",
"\n",
"Grocery_list = 'Grocery list: ' + ', '.join([food.lower() for food in food_list if food.lower().startswith('b')]) + '.'\n",
"\n",
"print(Grocery_list)\n",
"\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": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"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",
"\n",
"output_str = f\"{string1} {radius} {string2} {area(radius)}\"\n",
"\n",
"print(output_str)\n",
"\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": 5,
"metadata": {},
"outputs": [
{
"ename": "IndentationError",
"evalue": "unexpected indent (1460498202.py, line 11)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"C:\\Users\\Matheus Freire\\AppData\\Local\\Temp\\ipykernel_15140\\1460498202.py\"\u001b[1;36m, line \u001b[1;32m11\u001b[0m\n\u001b[1;33m words = poem.split()\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mIndentationError\u001b[0m\u001b[1;31m:\u001b[0m unexpected indent\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",
" words = poem.split()\n",
" unique_words = set(filter(lambda w: w not in blacklist, words))\n",
" \n",
" return unique_words\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": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"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",
"poem_words = re.findall(r'\\b[a-z]+\\b', poem.lower())\n",
"blacklist_set = set(blacklist)\n",
"filtered_words = [word for word in poem_words if word not in blacklist_set]\n",
"\n",
"print(filtered_words)\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": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['T', 'P']\n"
]
}
],
"source": [
"import re\n",
"\n",
"poem = \"\"\"The apparition of these faces in the crowd;\n",
"Petals on a wet, black bough.\"\"\"\n",
"\n",
"uppercase_chars = re.findall(r'[A-Z]', poem)\n",
"print(uppercase_chars)"
]
},
{
"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": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['123abc', 'abc123', 'JohnSmith1', 'ABBY4']\n"
]
}
],
"source": [
"data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n",
"\n",
"result = list(filter(lambda x: re.search('\\d', x), data))\n",
"print(result)"
]
},
{
"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": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['123abc', 'abc123', 'JohnSmith1']\n"
]
}
],
"source": [
"data = ['123abc', 'abc123', 'JohnSmith1', 'ABBY4', 'JANE']\n",
"\n",
"filtered_list = [s for s in data if re.search(r'\\d', s) and re.search(r'[a-z]', s)]\n",
"\n",
"print(filtered_list)\n"
]
}
],
"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.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Loading