diff --git a/lab-python-data-structures (1).ipynb b/lab-python-data-structures (1).ipynb new file mode 100644 index 0000000..4753aa8 --- /dev/null +++ b/lab-python-data-structures (1).ipynb @@ -0,0 +1,489 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lab | Data Structures " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 1: Working with Lists" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Imagine you are building a program for a teacher who wants to track the progress of their students throughout the semester. The teacher wants to input the grades of each student one by one, and get a summary of their performance. There are in total 5 students. You are tasked with building the program that will allow the teacher to do this easily.\n", + "\n", + "The program will prompt the teacher to enter the grades of each student. Once the teacher has entered all the grades, the program will calculate the total sum of the grades and display it on the screen. Then, the program will create a new list by selecting only the grades of the first, third, and fifth students entered by the teacher, and sort them in ascending order.\n", + "\n", + "Finally, the program will print out the new list, along with its length and the number of occurrences of the score 5 in the list. This will give the teacher a good overview of the performance of the selected students, and help them identify any potential issues early on." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Hint:*\n", + "- You can use the input() function to ask the user to enter their information.\n", + "- Look for list methods to perform the tasks. \n", + "- Remember, it is possible to get a part of the sequence using:\n", + "\n", + " ```python\n", + " sequence[x:y:z]\n", + " ```\n", + " where x, y, z are integers.\n", + "\n", + " The above returns a new sequence with the following characteristics:\n", + "\n", + " - A sequence with the same type as the original (a slice of a list is a list, a slice of a tuple is a tuple, and a slice of a string is a string).\n", + " - A sequence with elements from `sequence [x]` to `sequence [y-1]` (does not include a sequence [y]). By skipping `z` elements each time, it can be omitted if ` z = 1`.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Recommended External Resources:*\n", + "- *[Python Lists](https://www.w3schools.com/python/python_lists.asp)*\n", + "- *[Python List Methods](https://www.w3schools.com/python/python_ref_list.asp)*\n", + "- *[Python Built-in Functions](https://docs.python.org/3/library/functions.html)*\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter grades for 5 students (e.g., 5, 8, 10):\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Grade for student 1: 5\n", + "Grade for student 2: 8\n", + "Grade for student 3: 10\n", + "Grade for student 4: 12\n", + "Grade for student 5: 14\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Total sum of grades: 49\n", + "\n", + "Selected Grades (1st, 3rd, 5th) sorted: [5, 10, 14]\n", + "Number of selected grades: 3\n", + "Number of times grade 5 appears: 1\n" + ] + } + ], + "source": [ + "# Step 1: Initialize empty list for grades\n", + "grades = []\n", + "\n", + "# Step 2: Prompt teacher to enter grades for 5 students\n", + "print(\"Enter grades for 5 students (e.g., 5, 8, 10):\")\n", + "for i in range(1, 6):\n", + " grade = int(input(f\"Grade for student {i}: \"))\n", + " grades.append(grade)\n", + "\n", + "# Step 3: Calculate total sum of grades\n", + "total_sum = sum(grades)\n", + "print(f\"\\nTotal sum of grades: {total_sum}\")\n", + "\n", + "# Step 4: Select grades of 1st, 3rd, and 5th students (indexes 0, 2, 4)\n", + "selected_grades = grades[0:5:2]\n", + "\n", + "# Step 5: Sort the selected grades in ascending order\n", + "selected_grades.sort()\n", + "\n", + "# Step 6: Print the sorted selected list\n", + "print(f\"\\nSelected Grades (1st, 3rd, 5th) sorted: {selected_grades}\")\n", + "\n", + "# Step 7: Print length of the selected list\n", + "print(f\"Number of selected grades: {len(selected_grades)}\")\n", + "\n", + "# Step 8: Count how many times 5 appears\n", + "count_5 = selected_grades.count(5)\n", + "print(f\"Number of times grade 5 appears: {count_5}\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 2: Tuples" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Imagine you're running a fruit stand and want to keep track of your inventory. Write a Python program that does the following:\n", + "\n", + "- Initializes a tuple with 5 different types of fruit.\n", + "- Outputs the first and last elements of the tuple, so you can see the full range of fruits the store offers.\n", + "- Replaces the second element of the tuple with a new fruit that the store has recently received, and prints the updated tuple so you can see the changes.\n", + "- Concatenates a new tuple containing 2 additional fruits to the original tuple, so you can add them to the store inventory, and prints the resulting tuple to see the updated inventory.\n", + "- Splits the resulting tuple into 2 tuples of 3 elements each (the first tuple contains the first 3 elements, and the second tuple contains the last 3 elements), so you can organize the inventory more effectively.\n", + "- Combines the 2 tuples from the previous step with the original tuple into a new tuple, and prints the resulting tuple and its length, so you can see the final inventory after all the changes." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Recommended External Resources: [Python Tuples Examples and Methods](https://www.w3schools.com/python/python_tuples.asp)*\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First fruit: apple\n", + "Last fruit: mango\n", + "\n", + "Updated inventory after replacing second fruit: ('apple', 'kiwi', 'orange', 'grape', 'mango')\n", + "\n", + "Inventory after adding 2 new fruits: ('apple', 'kiwi', 'orange', 'grape', 'mango', 'pear', 'pineapple')\n", + "\n", + "First half (3 elements): ('apple', 'kiwi', 'orange')\n", + "Second half (3 elements): ('mango', 'pear', 'pineapple')\n", + "\n", + "Final combined inventory: ('apple', 'kiwi', 'orange', 'mango', 'pear', 'pineapple', 'apple', 'kiwi', 'orange', 'grape', 'mango', 'pear', 'pineapple')\n", + "Length of final inventory: 13\n" + ] + } + ], + "source": [ + "# Step 1: Initialize a tuple with 5 fruits\n", + "fruit_inventory = (\"apple\", \"banana\", \"orange\", \"grape\", \"mango\")\n", + "\n", + "# Step 2: Print first and last elements\n", + "print(\"First fruit:\", fruit_inventory[0])\n", + "print(\"Last fruit:\", fruit_inventory[-1])\n", + "\n", + "# Step 3: Replace the second element (\"banana\") with \"kiwi\"\n", + "# Tuples are immutable, so we need to convert to a list first\n", + "inventory_list = list(fruit_inventory)\n", + "inventory_list[1] = \"kiwi\"\n", + "fruit_inventory = tuple(inventory_list)\n", + "print(\"\\nUpdated inventory after replacing second fruit:\", fruit_inventory)\n", + "\n", + "# Step 4: Concatenate with 2 new fruits\n", + "new_fruits = (\"pear\", \"pineapple\")\n", + "fruit_inventory = fruit_inventory + new_fruits\n", + "print(\"\\nInventory after adding 2 new fruits:\", fruit_inventory)\n", + "\n", + "# Step 5: Split into 2 tuples of 3 elements each\n", + "first_half = fruit_inventory[:3]\n", + "second_half = fruit_inventory[-3:]\n", + "print(\"\\nFirst half (3 elements):\", first_half)\n", + "print(\"Second half (3 elements):\", second_half)\n", + "\n", + "# Step 6: Combine both halves and the full tuple into a final inventory\n", + "final_inventory = first_half + second_half + fruit_inventory\n", + "print(\"\\nFinal combined inventory:\", final_inventory)\n", + "print(\"Length of final inventory:\", len(final_inventory))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 3: Sets" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Imagine you are a data analyst working for a literature museum. Your manager has given you two poems to analyze, and she wants you to write a Python program to extract useful information from them.\n", + "\n", + "Your program should:\n", + "\n", + "- Create two sets, one for each poem, containing all unique words in both poems (ignoring case and punctuation).\n", + "- Print the number of unique words in each set.\n", + "- Identify and print the unique words present in the first poem but not in the second one.\n", + "- Identify and print the unique words present in the second poem but not in the first one.\n", + "- Identify and print the unique words present in both poems and print it in alphabetical order." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Recommended External Resources:*\n", + "- *[Python Sets](https://www.w3schools.com/python/python_sets.asp)* \n", + "- *[Python Set Methods](https://www.w3schools.com/python/python_ref_set.asp)*\n", + "- *[Python String Methods](https://www.w3schools.com/python/python_ref_string.asp)*\n" + ] + }, + { + "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", + "new_poem = \"\"\"Some say life is but a dream,\n", + "Some say it's a test.\n", + "From what I've seen and what I deem,\n", + "I side with those who see it as a quest.\n", + "\n", + "But if it had to end today,\n", + "I think I know enough of love,\n", + "To say that though it fades away,\n", + "It's still what we are made of.\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Unique words in poem 1: 11\n", + "Unique words in poem 2: 9\n", + "\n", + "Words only in Poem 1: {'and', 'blue', 'so', 'red', 'is', 'roses', 'sugar', 'sweet', 'violets'}\n", + "\n", + "Words only in Poem 2: {'star', 'wonder', 'little', 'i', 'twinkle', 'how', 'what'}\n", + "\n", + "Common words in both poems (alphabetical): ['are', 'you']\n" + ] + } + ], + "source": [ + "import string\n", + "\n", + "# Step 1: Define two sample poems\n", + "poem1 = \"Roses are red, violets are blue. Sugar is sweet, and so are you.\"\n", + "poem2 = \"Twinkle, twinkle, little star. How I wonder what you are!\"\n", + "\n", + "# Step 2: Preprocess and clean text: remove punctuation and lowercase\n", + "def clean_poem(poem):\n", + " return poem.translate(str.maketrans('', '', string.punctuation)).lower().split()\n", + "\n", + "# Step 3: Create sets of unique words\n", + "set1 = set(clean_poem(poem1))\n", + "set2 = set(clean_poem(poem2))\n", + "\n", + "# Step 4: Print number of unique words in each\n", + "print(\"Unique words in poem 1:\", len(set1))\n", + "print(\"Unique words in poem 2:\", len(set2))\n", + "\n", + "# Step 5: Words in poem 1 but not in poem 2\n", + "only_in_poem1 = set1 - set2\n", + "print(\"\\nWords only in Poem 1:\", only_in_poem1)\n", + "\n", + "# Step 6: Words in poem 2 but not in poem 1\n", + "only_in_poem2 = set2 - set1\n", + "print(\"\\nWords only in Poem 2:\", only_in_poem2)\n", + "\n", + "# Step 7: Words common to both poems (alphabetically sorted)\n", + "common_words = sorted(set1 & set2)\n", + "print(\"\\nCommon words in both poems (alphabetical):\", common_words)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 4: Dictionaries" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Consider the following dictionary of students with their scores in different subjects. One of the students, Bob, has complained about his score in Philosophy and, after reviewing it, the teacher has decided to update his score to 100. Write a Python program that updates Bob's score in Philosophy to 100 in the dictionary." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Recommended External Resources: [Python Dictionary Examples and Methods](https://www.w3schools.com/python/python_dictionaries.asp)*\n" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": {}, + "outputs": [], + "source": [ + "grades = {'Alice': {'Physics': 75, 'Math': 85, 'Chemistry': 60, 'Philosophy': 90}, 'Bob': {'Physics': 75, 'Math': 85, 'Chemistry': 60, 'Philosophy': 90}}" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Updated Grades:\n", + "{'Alice': {'Physics': 75, 'Math': 85, 'Chemistry': 60, 'Philosophy': 90}, 'Bob': {'Physics': 75, 'Math': 85, 'Chemistry': 60, 'Philosophy': 100}}\n" + ] + } + ], + "source": [ + "# Original dictionary of student grades\n", + "grades = {\n", + " 'Alice': {'Physics': 75, 'Math': 85, 'Chemistry': 60, 'Philosophy': 90},\n", + " 'Bob': {'Physics': 75, 'Math': 85, 'Chemistry': 60, 'Philosophy': 90}\n", + "}\n", + "\n", + "# Update Bob's Philosophy score to 100\n", + "grades['Bob']['Philosophy'] = 100\n", + "\n", + "# Print the updated dictionary\n", + "print(\"Updated Grades:\")\n", + "print(grades)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Bonus" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. Below are the two lists. Write a Python program to convert them into a dictionary in a way that item from list1 is the key and item from list2 is the value." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Hint: Use the zip() function. This function takes two or more iterables (like list, dict, string), aggregates them in a tuple, and returns it. Afterwards, you can use a function that turns a tuple into a dictionary.*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Recommended External Resources: [Python Zip Function](https://www.w3schools.com/python/ref_func_zip.asp)*\n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Subject Scores: {'Physics': 75, 'Math': 85, 'Chemistry': 60, 'Philosophy': 90}\n" + ] + } + ], + "source": [ + "keys = ['Physics', 'Math', 'Chemistry', 'Philosophy']\n", + "values = [75, 85, 60,90]\n", + "\n", + "# Given lists\n", + "keys = ['Physics', 'Math', 'Chemistry', 'Philosophy']\n", + "values = [75, 85, 60, 90]\n", + "\n", + "# Convert to dictionary using zip\n", + "subject_scores = dict(zip(keys, values))\n", + "\n", + "# Print the dictionary\n", + "print(\"Subject Scores:\", subject_scores)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2. Get the subject with the minimum score from the previous dictionary." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Hint: Use the built-in function min(). Read about the parameter key.*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "*Recommended External Resources:*\n", + "- *[Python Min Function Official Documentation](https://docs.python.org/3.8/library/functions.html#min)*\n", + "- *[How to use key function in max and min in Python](https://medium.com/analytics-vidhya/how-to-use-key-function-in-max-and-min-in-python-1fdbd661c59c)*" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python [conda env:base] *", + "language": "python", + "name": "conda-base-py" + }, + "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.12.7" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +}