Skip to content
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
243 changes: 216 additions & 27 deletions 02_activities/assignments/assignment_1.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,26 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 1,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n"
]
}
],
"source": [
"import hashlib\n",
"\n",
"def hash_to_range(input_string: str) -> int:\n",
" hash_object = hashlib.sha256(input_string.encode())\n",
" hash_int = int(hash_object.hexdigest(), 16)\n",
" return (hash_int % 3) + 1\n",
"input_string = \"your_first_name_here\"\n",
"result = hash_to_range(input_string)\n",
"input_string = \"vincent\"\n",
"result = hash_to_range(input_string) # \"vincent\" -> 2\n",
"print(result)\n"
]
},
Expand Down Expand Up @@ -112,13 +120,73 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def is_valid_brackets(s: str) -> bool:\n",
" # TODO\n",
" pass"
" # Check if the length of the input string is even\n",
" # If it's odd, we can immediately return False\n",
" if len(s) % 2 != 0:\n",
" return False\n",
" \n",
" # Use a stack to keep track of opening brackets\n",
" stack = []\n",
" bracket_map = {')': '(', '}': '{', ']': '['}\n",
"\n",
" for char in s:\n",
" # print(\"Current char:\", char)\n",
" # print(\"Current stack:\", stack)\n",
" if char in bracket_map.values(): \n",
" stack.append(char)\n",
" # print(f\"Append: {char} to stack:\", stack)\n",
" elif char in bracket_map.keys():\n",
" if stack == [] or bracket_map[char] != stack.pop():\n",
" # print(f\"Unmatched closing bracket: {char}\")\n",
" return False\n",
" # print(f\"Pop from stack for closing bracket:{bracket_map[char]} {char}\")\n",
" return stack == []"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Input: s = \"([]{})\"\n",
"Output: True\n",
"\n",
"Input: s = \"([)]\"\n",
"Output: False\n",
"\n",
"Input: s = \"()[]{}\"\n",
"Output: True\n",
"\n",
"Input: s = \"[{]}\"\n",
"Output: False\n"
]
}
],
"source": [
"\n",
"print(\"Input: s = \\\"([]{})\\\"\")\n",
"print(\"Output:\", is_valid_brackets(\"([]{})\"))\n",
"\n",
"# print(is_valid_brackets(\"([)]\")) # False\n",
"print(\"\\nInput: s = \\\"([)]\\\"\")\n",
"print(\"Output:\", is_valid_brackets(\"([)]\"))\n",
"\n",
"# print(is_valid_brackets(\"()[]{}\")) # True\n",
"print(\"\\nInput: s = \\\"()[]{}\\\"\")\n",
"print(\"Output:\", is_valid_brackets(\"()[]{}\"))\n",
"\n",
"# print(is_valid_brackets(\"[{]}\")) # False\n",
"print(\"\\nInput: s = \\\"[{]}\\\"\")\n",
"print(\"Output:\", is_valid_brackets(\"[{]}\"))\n"
]
},
{
Expand Down Expand Up @@ -169,7 +237,7 @@
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"# Look at a bracket only string and make sure every opening bracket is closed by the same type in the right sequence."
]
},
{
Expand All @@ -181,11 +249,32 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 4,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Input: s = \"{[()()][]}\"\n",
"Output: True\n",
"\n",
"Input: s = \"((({[}))\"\n",
"Output: False\n"
]
}
],
"source": [
"# Your answer here"
"# Input: s = \"{[()()][]}\"\n",
"# Output: True\n",
"print(\"\\nInput: s = \\\"{[()()][]}\\\"\")\n",
"print(\"Output:\", is_valid_brackets(\"{[()()][]}\"))\n",
"\n",
"# Input: s = \"((({[}))\"\n",
"# Output: False\n",
"print(\"\\nInput: s = \\\"((({[}))\\\"\")\n",
"print(\"Output:\", is_valid_brackets(\"((({[}))\"))\n"
]
},
{
Expand All @@ -202,7 +291,38 @@
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"def is_valid_brackets(s: str) -> bool:\n",
" \"\"\"\n",
" Checks if a string of brackets is valid using a Stack ADT.\n",
"\n",
" Args:\n",
" s: The input string containing brackets.\n",
"\n",
" Returns:\n",
" True if the brackets are valid, False otherwise.\n",
" \"\"\"\n",
" # An odd-length string can't have matching pairs.\n",
" if len(s) % 2 != 0:\n",
" return False\n",
"\n",
" # The Stack ADT is implemented using a Python list.\n",
" stack = []\n",
" # A map to hold the matching bracket pairs.\n",
" bracket_map = {')': '(', '}': '{', ']': '['}\n",
"\n",
" for char in s:\n",
" # If it's an opening bracket push it onto the stack.\n",
" if char in bracket_map.values():\n",
" stack.append(char)\n",
" # If it's a closing bracket...\n",
" elif char in bracket_map.keys():\n",
" # The stack can't be empty and the top of the stack\n",
" # must be the matching opening bracket.\n",
" if not stack or bracket_map[char] != stack.pop():\n",
" return False\n",
"\n",
" # If the stack is empty all brackets were matched.\n",
" return not stack\n"
]
},
{
Expand All @@ -214,12 +334,12 @@
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"- The code leverages the Stack ADT. \n",
"- The Last-In, First-Out (LIFO) nature of a stack ensures that the most recently opened bracket is the first one that must be closed. \n",
"- This mirrors the nested structure of valid brackets like ({[]})."
]
},
{
Expand All @@ -231,12 +351,17 @@
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"Time Complexity: O(n)\n",
"- The algorithm iterates through the input string of length n exactly once. \n",
"- Each operation inside the loop—appending to a list (push), popping from a list (pop) and dictionary lookups—takes constant time. \n",
"- The total time complexity is proportional to the length of the string.\n",
"\n",
"Space Complexity: O(n)\n",
"- In the worst-case scenario such as the string \"(((((\", all characters are opening brackets and will be pushed onto the stack. \n",
"- The space required by the stack will be proportional to the length of the input string, n."
]
},
{
Expand All @@ -249,11 +374,75 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"# Each pass strips all immediately-adjacent matches\n",
"# If anything is left at the end then some opener and closer brackets are mismatched. \n",
"# The remaining brackets indicate that the string isn’t valid.\n",
"\n",
"# Time Complexity\n",
"# The replace method scans the entire string to find and replace substrings. \n",
"# In the worst case, this operation takes O(n) time for a string of length n.\n",
"# The while loop continues until no more replacements can be made. \n",
"# In the worst case, the loop runs n/2 times where each pass removes one pair of brackets.\n",
"# Therefore, the total time complexity is O(n^2) in the worst case.\n",
"\n",
"# Space Complexity\n",
"# The replace method creates a new string each time it is called which requires O(n) space for the new string.\n",
"# Therefore, the space complexity is O(n).\n",
"\n",
"# Time Complexity: O(n^2)\n",
"# Space Complexity: O(n)\n",
"\n",
"def is_valid_brackets_pairs(s: str) -> bool:\n",
" prev = None\n",
" while prev != s:\n",
" prev = s\n",
" s = (\n",
" s.replace(\"()\", \"\")\n",
" .replace(\"[]\", \"\")\n",
" .replace(\"{}\", \"\")\n",
" )\n",
" return not s"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Input: s = \"([]{})\"\n",
"Output: True\n",
"\n",
"Input: s = \"([)]\"\n",
"Output: False\n",
"\n",
"Input: s = \"()[]{}\"\n",
"Output: True\n",
"\n",
"Input: s = \"[{]}\"\n",
"Output: False\n"
]
}
],
"source": [
"print(\"Input: s = \\\"([]{})\\\"\")\n",
"print(\"Output:\", is_valid_brackets_pairs(\"([]{})\"))\n",
"\n",
"print(\"\\nInput: s = \\\"([)]\\\"\")\n",
"print(\"Output:\", is_valid_brackets_pairs(\"([)]\"))\n",
"\n",
"print(\"\\nInput: s = \\\"()[]{}\\\"\")\n",
"print(\"Output:\", is_valid_brackets_pairs(\"()[]{}\"))\n",
"\n",
"print(\"\\nInput: s = \\\"[{]}\\\"\")\n",
"print(\"Output:\", is_valid_brackets_pairs(\"[{]}\"))\n"
]
},
{
Expand Down Expand Up @@ -290,9 +479,9 @@
" * Open a private window in your browser. Copy and paste the link to your pull request into the address bar. Make sure you can see your pull request properly. This helps the technical facilitator and learning support staff review your submission easily.\n",
"\n",
"Checklist:\n",
"- [ ] Create a branch called `assignment-1`.\n",
"- [ ] Ensure that the repository is public.\n",
"- [ ] Review [the PR description guidelines](https://github.com/UofT-DSI/onboarding/blob/main/onboarding_documents/submissions.md#guidelines-for-pull-request-descriptions) and adhere to them.\n",
"- [X] Create a branch called `assignment-1`.\n",
"- [X] Ensure that the repository is public.\n",
"- [X] Review [the PR description guidelines](https://github.com/UofT-DSI/onboarding/blob/main/onboarding_documents/submissions.md#guidelines-for-pull-request-descriptions) and adhere to them.\n",
"- [ ] Verify that the link is accessible in a private browser window.\n",
"\n",
"If you encounter any difficulties or have questions, please don't hesitate to reach out to our team via our Slack at `#cohort-3-help`. Our Technical Facilitators and Learning Support staff are here to help you navigate any challenges."
Expand All @@ -301,7 +490,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "dsi_participant",
"language": "python",
"name": "python3"
},
Expand All @@ -315,7 +504,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
"version": "3.12.3"
}
},
"nbformat": 4,
Expand Down
Loading