Skip to content
Closed
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
62 changes: 54 additions & 8 deletions 02_activities/assignments/assignment_1.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,31 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 46,
"metadata": {},
"outputs": [],
"source": [
"from typing import List\n",
"\n",
"def first_duplicate(nums: List[int]) -> int:\n",
" # TODO\n",
" pass"
" num_set = set()\n",
" for num in nums:\n",
" if num in num_set:\n",
" return num\n",
" else:\n",
" num_set.add(num)\n",
" return -1\n"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"assert first_duplicate([3, 1, 4, 2, 5, 1, 6]) == 1\n",
"assert first_duplicate([7, 8, 9, 10]) == -1\n",
"assert first_duplicate([4, 5, 6, 4, 6]) == 4"
]
},
{
Expand Down Expand Up @@ -112,13 +128,40 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 67,
"metadata": {},
"outputs": [],
"source": [
"def bracket_matches(b1:str, b2:str):\n",
" if b1 == '(' and b2 == ')' or b1 == '[' and b2 == ']' or b1 == '{' and b2 == '}':\n",
" return True\n",
" else:\n",
" return False\n",
"\n",
"def is_valid_brackets(s: str) -> bool:\n",
" # TODO\n",
" pass"
" stack = []\n",
" for brack in s:\n",
" if brack == '(' or brack == '[' or brack == '{':\n",
" stack.append(brack)\n",
" elif stack:\n",
" opening_brack = stack.pop()\n",
" if not bracket_matches(opening_brack, brack):\n",
" return False\n",
" else:\n",
" return False\n",
" return len(stack) == 0\n"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [],
"source": [
"assert is_valid_brackets(\"([]{})\") == True\n",
"assert is_valid_brackets(\"([)]\") == False\n",
"assert is_valid_brackets(\"()[]{}\") == True\n",
"assert is_valid_brackets(\"[{]}\") == False\n"
]
},
{
Expand Down Expand Up @@ -300,8 +343,11 @@
}
],
"metadata": {
"interpreter": {
"hash": "7ccc5368cda896b2ab91e5e6fe72ec210001cb3dc1ca1ba63746389bd9a7a2c9"
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3.11.14 64-bit (system)",
"language": "python",
"name": "python3"
},
Expand All @@ -315,7 +361,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
"version": "3.11.14"
}
},
"nbformat": 4,
Expand Down