{ "cells": [ { "cell_type": "markdown", "id": "cceb0c53-86e0-416b-b626-c8ba5e2f3695", "metadata": {}, "source": [ "###
San Jose State University
Department of Applied Data Science

**DATA 200
Computational Programming for Data Analytics**

Spring 2023
Instructor: Ron Mak

**Assignment #4: List Practice**

SAMPLE SOLUTIONS
" ] }, { "cell_type": "markdown", "id": "bdacc22c-884f-4db0-8e4f-d5f8552900ec", "metadata": {}, "source": [ "#### Solve each of the following Python programming problems using only list operations and list methods. Do not use any other Python data structures such as dictionaries or sets." ] }, { "cell_type": "markdown", "id": "54960783-b919-4b54-8ddc-aa03414fff57", "metadata": {}, "source": [ "#### **PROBLEM 1:** [20 points] Define a function `swap_halves()` that has one parameter whose value you may assume is a list. If the list has an even length, the function should swap the first half of the list with the second half, and return the modified list. If the list has an odd number of elements, the function should first append a element with value 0 at the end of the list, and then perform the swap and return.\n", "\n", "#### For example, if your function is passed the value `[1, 2, 3, 4, 5, 6]`, it should return the list `[4, 5, 6, 1, 2, 3]`.\n", "\n", "#### Test your function with at least the following lists:\n", "- `[1, 2, 3, 4, 5, 6]`\n", "- `[12, 56, 33, 81, 33, 94, 56]`\n", "- `['Hello', ', ', 'world!']`\n", "- `[1]`\n", "- `[]`" ] }, { "cell_type": "code", "execution_count": null, "id": "c62ba073-98e6-49a8-8ea9-2f8ae4fe0a05", "metadata": {}, "outputs": [], "source": [ "a = 3\n", "b = 7\n", "\n", "(a, b) = (b, a)" ] }, { "cell_type": "code", "execution_count": null, "id": "5cf2fd9d-9939-4aee-b4ae-f956027d2c1c", "metadata": {}, "outputs": [], "source": [ "a" ] }, { "cell_type": "code", "execution_count": null, "id": "37411846-b6c5-45fe-bfb3-f4c5147c1b31", "metadata": {}, "outputs": [], "source": [ "b" ] }, { "cell_type": "code", "execution_count": null, "id": "48646ca7-621d-4e68-baa0-5c3c35150a84", "metadata": {}, "outputs": [], "source": [ "def swap_halves(lst):\n", " \"\"\"\n", " Swap the two haves of a list. If the list is odd-sized,\n", " first append a 0.\n", " \"\"\"\n", " if len(lst)%2 == 1:\n", " lst.append(0)\n", " \n", " half_len = len(lst)//2\n", " \n", " for i in range(half_len):\n", " lst[i], lst[i + half_len] = lst[i + half_len], lst[i]\n", " \n", " return lst" ] }, { "cell_type": "code", "execution_count": null, "id": "f1e19b1e-4f24-4254-a9e3-ebda630a6764", "metadata": {}, "outputs": [], "source": [ "print(swap_halves([1, 2, 3, 4, 5, 6]))" ] }, { "cell_type": "code", "execution_count": null, "id": "bec6fea8-835b-4a3c-aeba-e59bd72e8384", "metadata": {}, "outputs": [], "source": [ "print(swap_halves([12, 56, 33, 81, 33, 94, 56]))" ] }, { "cell_type": "code", "execution_count": null, "id": "fdc2dadb-2032-4045-90b7-1992679f5257", "metadata": {}, "outputs": [], "source": [ "print(swap_halves(['Hello', ', ', 'world!']))" ] }, { "cell_type": "code", "execution_count": null, "id": "d68a437e-aeec-49cc-b95a-289867c8776c", "metadata": {}, "outputs": [], "source": [ "print(swap_halves([1]))" ] }, { "cell_type": "code", "execution_count": null, "id": "b08012c0-972e-42e2-956a-41d030e27ec1", "metadata": {}, "outputs": [], "source": [ "print(swap_halves([]))" ] }, { "cell_type": "markdown", "id": "c60f47db-016b-4486-bee5-0da45178b230", "metadata": {}, "source": [ "#### **PROBLEM 2:** [20 points] Define a function `similar_lists()` that has two parameters whose values you may assume are lists of integer values. The function should check whether the two lists are similar -- they contain the same element values ignoring order and duplicates -- and return `True` if they are similar or `False` otherwise. Your function should **not** modify the lists that are passed to it.\n", "\n", "#### For example, the two lists\n", "- `[1, 4, 9, 16, 9, 7, 4, 9, 11]`\n", "- `[11, 11, 7, 9, 16, 4, 1]`\n", "#### are similar. But\n", "- `[11, 11, 7, 9, 16, 4, 1]`\n", "- `[9, 7, 11, 1, 8, 4, 16]`\n", "#### are not.\n", "\n", "#### Test your function with at least the above two pairs of lists." ] }, { "cell_type": "code", "execution_count": null, "id": "0c8e4512-ea64-4b9d-86e1-282fae4e158c", "metadata": {}, "outputs": [], "source": [ "def find_match(target_elmt, lst):\n", " \"\"\"\n", " Return True if the target_elmt is in the list lst.\n", " Otherwise, return False.\n", " \"\"\"\n", " for elmt in lst:\n", " if elmt == target_elmt:\n", " return True\n", " \n", " return False" ] }, { "cell_type": "code", "execution_count": null, "id": "6b496cab-7e5e-4f76-95d8-1988cca1abef", "metadata": {}, "outputs": [], "source": [ "find_match(7, [1, 4, 9, 16, 9, 7, 4, 9, 11])" ] }, { "cell_type": "code", "execution_count": null, "id": "28371ab2-c47c-49d2-9ed7-c26478f5f48b", "metadata": {}, "outputs": [], "source": [ "find_match(5, [1, 4, 9, 16, 9, 7, 4, 9, 11])" ] }, { "cell_type": "code", "execution_count": null, "id": "3e52558d-6a84-4b8d-ac58-0ca86e79bd93", "metadata": {}, "outputs": [], "source": [ "def check_lists(lst1, lst2):\n", " \"\"\"\n", " Return True if each element of list lst1 is in list lst2.\n", " Otherwise, return False.\n", " \"\"\"\n", " for elmt in lst1:\n", " if not find_match(elmt, lst2):\n", " return False\n", " \n", " return True" ] }, { "cell_type": "code", "execution_count": null, "id": "3a448816-e186-4575-ba03-c70efab6de82", "metadata": {}, "outputs": [], "source": [ "lst1 = [1, 4, 9, 16, 9, 7, 4, 9, 11]\n", "lst2 = [11, 11, 7, 9, 16, 4, 1]\n", "\n", "print(check_lists(lst1, lst2))\n", "print(check_lists(lst2, lst1))" ] }, { "cell_type": "code", "execution_count": null, "id": "671d2bcd-14b4-419c-a80a-fd874910fe53", "metadata": {}, "outputs": [], "source": [ "lst1 = [11, 11, 7, 9, 16, 4, 1]\n", "lst2 = [9, 7, 11, 1, 8, 4, 16]\n", "\n", "print(check_lists(lst1, lst2))\n", "print(check_lists(lst2, lst1))" ] }, { "cell_type": "code", "execution_count": null, "id": "f6bc0795-5e8b-46d4-8a77-d135438bf033", "metadata": {}, "outputs": [], "source": [ "def similar_lists(lst1, lst2):\n", " \"\"\"\n", " Return True if the two lists lst1 and lst2 to similar.\n", " Otherwise, return False.\n", " \"\"\"\n", " return check_lists(lst1, lst2) and check_lists(lst2, lst1)" ] }, { "cell_type": "code", "execution_count": null, "id": "57f433fc-dea2-4a1b-95ad-089b233c1c33", "metadata": {}, "outputs": [], "source": [ "list_1 = [1, 4, 9, 16, 9, 7, 4, 9, 11]\n", "list_2 = [11, 11, 7, 9, 16, 4, 1]\n", "\n", "similar_lists(list_1, list_2)" ] }, { "cell_type": "code", "execution_count": null, "id": "08b49846-a082-456e-a33e-faa162cedb1b", "metadata": {}, "outputs": [], "source": [ "list_1 = [11, 11, 7, 9, 16, 4, 1]\n", "list_2 = [9, 7, 11, 1, 8, 4, 16]\n", "\n", "similar_lists(list_1, list_2)" ] }, { "cell_type": "code", "execution_count": null, "id": "720fdca2-637c-4f34-99a9-64749756c983", "metadata": {}, "outputs": [], "source": [ "list_1 = [11, 11, 7, 9, 16, 4, 1]\n", "list_2 = []\n", "\n", "similar_lists(list_1, list_2)" ] }, { "cell_type": "code", "execution_count": null, "id": "bfd216c8-0dc3-4619-82a7-0267871a34c9", "metadata": {}, "outputs": [], "source": [ "list_1 = []\n", "list_2 = [9, 7, 11, 1, 8, 4, 16]\n", "\n", "similar_lists(list_1, list_2)" ] }, { "cell_type": "code", "execution_count": null, "id": "0e9fd1b8-5177-4011-96a6-a718648f029f", "metadata": {}, "outputs": [], "source": [ "list_1 = []\n", "list_2 = []\n", "\n", "similar_lists(list_1, list_2)" ] }, { "cell_type": "markdown", "id": "5c39e9d3-8f05-49cd-b686-fda230ce6987", "metadata": {}, "source": [ "#### **PROBLEM 3:** [20 points] Write Python code that simulates rolling a fair die 20 times and looking for runs. A run is a sequence of adjacent repeated values. Your program should generate 20 random die rolls and store the values into a list. Then it should print the values from the list, enclosing the runs in parentheses.\n", "\n", "#### Example: `1 2 ( 5 5 ) 3 1 2 4 3 ( 2 2 2 2 ) 3 6 ( 1 1 ) 6 3 2`" ] }, { "cell_type": "code", "execution_count": null, "id": "73b6534f-c85c-40a2-81d9-c91779faa070", "metadata": {}, "outputs": [], "source": [ "def print_run(i, lst):\n", " \"\"\"\n", " Print a run that starts at index i.\n", " Enclose the run parentheses.\n", " Return the ending index of the run.\n", " \"\"\"\n", " print(f' ({lst[i]:2}', end ='')\n", " \n", " # Loop until the end of the run.\n", " while (i < len(lst) - 1) and (lst[i] == lst[i + 1]):\n", " print(f'{lst[i + 1]:2}', end = '')\n", " i += 1\n", " \n", " print(' )', end='')\n", " return i " ] }, { "cell_type": "code", "execution_count": null, "id": "1de291d0-88b7-4144-8684-e38c2926a33b", "metadata": {}, "outputs": [], "source": [ "print_run(3, [0, 1, 2, 6, 6, 6, 6, 6, 9])" ] }, { "cell_type": "code", "execution_count": null, "id": "a46d064c-1e9e-42c0-a22d-d222a4cc8bf1", "metadata": {}, "outputs": [], "source": [ "print_run(3, [0, 1, 2, 6, 6, 6])" ] }, { "cell_type": "code", "execution_count": null, "id": "79ceffad-2b47-4563-8b48-de9ef39dd0e5", "metadata": {}, "outputs": [], "source": [ "import random\n", "\n", "def test_runs():\n", " \"\"\"\n", " Test printing simulated die throws\n", " with runs enclosed in parentheses.\n", " \"\"\"\n", " rolls = [ random.randrange(1, 7) for _ in range(20) ]\n", " \n", " # Print the rolls.\n", " for r in rolls:\n", " print(f'{r:2}', end='')\n", " print()\n", "\n", " i = 0\n", " length = len(rolls)\n", "\n", " # Loop over the list of random roll values.\n", " while i < length:\n", " \n", " # Look for the start of a run.\n", " if (i < length - 1) and rolls[i] == rolls[i + 1]:\n", " i = print_run(i, rolls) # start of a run\n", " else:\n", " print(f'{rolls[i]:2}', end='') # not a run\n", " \n", " i += 1" ] }, { "cell_type": "code", "execution_count": null, "id": "a134139f-7074-4166-9f5a-8761d884a743", "metadata": {}, "outputs": [], "source": [ "for _ in range(25):\n", " test_runs()\n", " print()\n", " print()" ] }, { "cell_type": "markdown", "id": "369282a2-7af6-473a-a10d-29e68686a9aa", "metadata": {}, "source": [ "#### **PROBLEM 4.a:** [20 points] Consider the following population data. \n", "####
**Population Per Continent (in millions)**
\n", "| Year | 1750 | 1800 | 1850 | 1900 | 1950 | 2000 | 2050 |\n", "| --- | --: | --: | --: | --: | --: | --: | --: |\n", "| **Africa** | 106 | 107 | 111 | 133 | 221 | 767 | 1766 |\n", "| **Asia** | 502 | 635 | 809 | 947 | 1402 | 3634 | 5268 |\n", "| **Australia** | 2 | 2 | 2 | 6 | 13 | 30 | 46 |\n", "| **Europe** | 163 | 203 | 276 | 408 | 547 | 729 | 628 |\n", "| **North America** | 2 | 7 | 26 | 82 | 172 | 307 | 392 |\n", "| **South America** | 16 | 24 | 38 | 74 | 167 | 511 | 809 |\n", "#### Represent the data as a two-dimensional list. Include the column headers and the continent names, but not the table title." ] }, { "cell_type": "code", "execution_count": null, "id": "a48fc7e2-03d2-44c5-9009-3a0c46c75e09", "metadata": {}, "outputs": [], "source": [ "population = [\n", " ['Year', 1750, 1800, 1850, 1900, 1950, 2000, 2050],\n", " ['Africa', 106, 107, 111, 133, 221, 767, 1766],\n", " ['Asia', 502, 635, 809, 947, 1402, 3634, 5268],\n", " ['Australia', 2, 2, 2, 6, 13, 30, 46],\n", " ['Europe', 163, 203, 276, 408, 547, 729, 628],\n", " ['North America', 2, 7, 26, 82, 172, 307, 392],\n", " ['South America', 16, 24, 38, 74, 167, 511, 809]\n", "]\n", "\n", "population" ] }, { "cell_type": "markdown", "id": "78296d12-00ee-420b-8fce-8b75e8dfd77c", "metadata": {}, "source": [ "#### **PROBLEM 4.b:** [20 points] Print the two-dimensional list as a neatly formatted table. Add column totals as a new bottom row that show the world population in the given years." ] }, { "cell_type": "code", "execution_count": null, "id": "5cf04106-b745-4260-8ca1-b168364d9025", "metadata": {}, "outputs": [], "source": [ "# Initiaize list totals to all zeros.\n", "totals = [0]*8\n", "totals" ] }, { "cell_type": "code", "execution_count": null, "id": "017c8263-7939-41ba-994b-b15598121aba", "metadata": {}, "outputs": [], "source": [ "headers = population[0]\n", "headers" ] }, { "cell_type": "code", "execution_count": null, "id": "aa434378-23be-433d-9434-87311de034a0", "metadata": {}, "outputs": [], "source": [ "# Print the column headers.\n", "print(f'{headers[0]:15}', end='')\n", "for col_index in range(1, len(headers)):\n", " print(f'{headers[col_index]:7}', end='')\n", "print()\n", "print()\n", "\n", "# Print each row. Sum each column.\n", "for row_index in range(1, len(population)):\n", " row = population[row_index]\n", " print(f'{row[0]:15}', end='')\n", " \n", " for col_index in range(1, len(row)):\n", " print(f'{row[col_index]:7d}', end='')\n", " totals[col_index] += row[col_index]\n", " \n", " print()\n", "\n", "print()\n", "print(' '*15, end='')\n", "\n", "# Print the column totals.\n", "for col_index in range(1, len(totals)):\n", " print(f'{totals[col_index]:7}', end='')\n", " \n", "print()" ] }, { "cell_type": "markdown", "id": "2bcd7467-50d6-4ceb-a3d8-ad94e348d5d5", "metadata": {}, "source": [ "#### A fancier table that demonstrates dynamic (i.e., determined at run time) print widths and string repetition, and commas in printed numbers.\n", "\n", "#### Example dynamic print width:\n", "``` python\n", "{headers[0]:{max_cont_len + 1}}\n", "```\n", "#### Note that the width expression must be enclosed in curly braces.\n", "\n", "#### Example string repetition:\n", "``` python\n", "'-'*(num_width*7)\n", "```\n", "\n", "#### Example format specification to print an integer with commas:\n", "``` python\n", "{row[col_index]:{num_width},d}\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "8e0c66f6-509b-4e3b-b325-dd0d9eef5876", "metadata": {}, "outputs": [], "source": [ "conts = ('Africa', 'Asia', 'Australia', 'Europe', 'North America', 'South America')\n", "\n", "# Calculate the maximum length of a continent name.\n", "max_cont_len = max([ len(cont) for cont in conts ])\n", "max_cont_len" ] }, { "cell_type": "code", "execution_count": null, "id": "755f2e2f-9417-4c09-aefa-a1dd4c958edb", "metadata": {}, "outputs": [], "source": [ "#### Print width for numbers.\n", "num_width = 7" ] }, { "cell_type": "code", "execution_count": null, "id": "06b82be7-7f70-4b13-86ec-9d9dfb2d3c2f", "metadata": {}, "outputs": [], "source": [ "population = [\n", " ['Year', 1750, 1800, 1850, 1900, 1950, 2000, 2050],\n", " [conts[0], 106, 107, 111, 133, 221, 767, 1766],\n", " [conts[1], 502, 635, 809, 947, 1402, 3634, 5268],\n", " [conts[2], 2, 2, 2, 6, 13, 30, 46],\n", " [conts[3], 163, 203, 276, 408, 547, 729, 628],\n", " [conts[4], 2, 7, 26, 82, 172, 307, 392],\n", " [conts[5], 16, 24, 38, 74, 167, 511, 809]\n", "]\n", "\n", "population" ] }, { "cell_type": "code", "execution_count": null, "id": "4a97ec16-6b4b-4055-917e-a89670594ce2", "metadata": {}, "outputs": [], "source": [ "headers = population[0]\n", "headers" ] }, { "cell_type": "code", "execution_count": null, "id": "17298f2a-3c7f-4012-9b02-ae0f847af0ab", "metadata": {}, "outputs": [], "source": [ "totals = [0]*8\n", "\n", "# Print the column headers.\n", "print(f'{headers[0]:{max_cont_len + 1}}|', end='')\n", "for col_index in range(1, len(headers)):\n", " print(f'{headers[col_index]:{num_width}}', end='')\n", "print()\n", "print(f\"{'-'*(max_cont_len + 1)}+{'-'*(num_width*7)}\")\n", "\n", "# Print each row. Sum each column.\n", "for row_index in range(1, len(population)):\n", " row = population[row_index]\n", " \n", " print(f'{row[0]:{max_cont_len + 1}}|', end='')\n", " \n", " for col_index in range(1, len(row)):\n", " print(f'{row[col_index]:{num_width},d}', end='')\n", " totals[col_index] += row[col_index]\n", "\n", " print()\n", " \n", "# Print the column totals.\n", "print(f\"{' '*(max_cont_len + 1)}{'+'}{'-'*(num_width*7)}\", end='')\n", "print()\n", "print(f\"{' '*(max_cont_len + 2)}\", end='')\n", "for col_index in range(1, len(totals)):\n", " print(f'{totals[col_index]:{num_width},d}', end='') \n", " \n", "print()" ] } ], "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": 5 }