Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
P
Pyeng Lectures
Manage
Activity
Members
Labels
Plan
Issues
0
Issue boards
Milestones
Wiki
Code
Merge requests
0
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package Registry
Container Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Terms and privacy
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Riccardo Caracciolo
Pyeng Lectures
Commits
f5b9aed7
Commit
f5b9aed7
authored
4 months ago
by
Jöran Frey
Browse files
Options
Downloads
Patches
Plain Diff
added solution week 5 added content to lecture
parent
dbd77cfd
No related branches found
Branches containing commit
No related tags found
No related merge requests found
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
unit-4/Exercises/50_Solution_Week5 - Control structures copy.ipynb
+409
-0
409 additions, 0 deletions
...ercises/50_Solution_Week5 - Control structures copy.ipynb
unit-5/JSON example/employeesheet.json
+39
-0
39 additions, 0 deletions
unit-5/JSON example/employeesheet.json
with
448 additions
and
0 deletions
unit-4/Exercises/50_Solution_Week5 - Control structures copy.ipynb
0 → 100644
+
409
−
0
View file @
f5b9aed7
{
"cells": [
{
"cell_type": "markdown",
"id": "41ad2b77",
"metadata": {},
"source": [
"### 1.1 Namespace basic\n",
"\n",
"Create a function that contains a nested function.\n",
"For each space (Global, outer-, and inner Function) define the variable a with different values e.g., 1,2,3 <br>\n",
"Show how the namespaces are separated from each other by using the print function in different spaces.\n",
"\n",
"call the outer function ``outer_function`` and the inner function``inner_function``"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "aa5b4c1f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Inner function scope 'a' = 3\n",
"Outer function scope 'a' = 2\n",
"Global scope 'a' = 1\n"
]
}
],
"source": [
"# global\n",
"a = 1\n",
"\n",
"def outer_function():\n",
" # outer function\n",
" a = 2\n",
" \n",
" def inner_function():\n",
" # inner function\n",
" a = 3\n",
" print(f\"Inner function scope 'a' = {a}\") # This will print the inner scope variable 'a'\n",
" \n",
" inner_function()\n",
" print(f\"Outer function scope 'a' = {a}\") # This will print the outer scope variable 'a'\n",
"\n",
"# Call the outer function\n",
"outer_function()\n",
"\n",
"# Print the global scope variable 'a'\n",
"print(f\"Global scope 'a' = {a}\")"
]
},
{
"cell_type": "markdown",
"id": "0a1c4f0d",
"metadata": {},
"source": [
"1.2 Namespace using ``global`` and ``nonlocal``"
]
},
{
"cell_type": "markdown",
"id": "ad3e2e48",
"metadata": {},
"source": [
"### 2.1 Declaration of data collections\n",
"Create variables with basic data types with the following names, which can store the corresponding value:\n",
"\n",
"- the verbs swim run dance\n",
"- The GPS coordinates: 47.2286, 8.8317\n",
"- The definition of a person with name, age, canton of residence"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "9f98d24d",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Verbs: ['swim', 'run', 'dance']\n",
"GPS Coordinates: (47.2286, 8.8317)\n",
"Person: {'name': 'John Doe', 'age': 30, 'canton': 'St. Gallen'}\n"
]
}
],
"source": [
"#list to store the verbs: swim, run, dance\n",
"verbs = [\"swim\", \"run\", \"dance\"]\n",
"\n",
"#tuple to store the GPS coordinates (latitude, longitude)\n",
"gps_coordinates = (47.2286, 8.8317)\n",
"\n",
"# A dictionary to store a definition\n",
"person = {\n",
" \"name\": \"John Doe\", \n",
" \"age\": 30, \n",
" \"canton\": \"St. Gallen\" \n",
"}\n",
"\n",
"# Display the variables\n",
"print(\"Verbs:\", verbs)\n",
"print(\"GPS Coordinates:\", gps_coordinates)\n",
"print(\"Person:\", person)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "b01c0156",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Updated student dictionary: {'age': 22, 'major': 'social work', 'graduation_year': 2025}\n"
]
}
],
"source": [
"# Initial \n",
"student = {\n",
" \"name\": \"Anna\",\n",
" \"age\": 22,\n",
" \"major\": \"social work\"\n",
"}\n",
"\n",
"# Add the key \"graduation_year\"\n",
"student[\"graduation_year\"] = 2025\n",
"\n",
"# Remove the \"age\" key \n",
"student.pop(\"name\")\n",
"\n",
"# Print the updated dictionary\n",
"print(\"Updated student dictionary:\", student)"
]
},
{
"cell_type": "markdown",
"id": "93970c5b",
"metadata": {},
"source": [
"### 2.3 Loop Through a Dictionary\n",
"\n",
"Given the dictionary:\n",
"\n",
"```python\n",
"movie = {x\n",
" \"title\": \"Inception\",\n",
" \"director\": \"Christopher Nolan\",\n",
" \"release_year\": 2010\n",
"}\n",
"```\n",
"\n",
"Write a Python program that loops through the dictionary and prints both the keys and their corresponding values."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "61004b7b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"title: Inception\n",
"director: Christopher Nolan\n",
"release_year: 2010\n"
]
}
],
"source": [
"movie = {\n",
" \"title\": \"Inception\",\n",
" \"director\": \"Christopher Nolan\",\n",
" \"release_year\": 2010\n",
"}\n",
"\n",
"# Loop through the dictionary and print both keys and values\n",
"for key, value in movie.items():\n",
" print(f\"{key}: {value}\")"
]
},
{
"cell_type": "markdown",
"id": "6b25596c",
"metadata": {},
"source": [
"### 2.4 Checking the availability of screws in the warehouse\n",
"\n",
"Define a ``screw_warehouse_manager`` function that checks whether a particular screw exists in the warehouse and whether it is in stock.\n",
"\n",
"### Task\n",
"\n",
"1. **Dictionary**\n",
" - Given is a dictionary 'screw warehouse' that contains different screw types and their available quantities.\n",
"\n",
"2. **Implement function**\n",
" - Implement the function `Screw_warehouse_manager(screw)`, which performs the following checks:\n",
" - If the screw is available in stock and the quantity is greater than 0, the function returns `“in stock”`.\n",
" - If the screw is in stock but the quantity is 0, the function returns “out of stock”.\n",
" - If the screw is not in stock, the function returns `“does not exist”`."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "149d200c",
"metadata": {},
"outputs": [],
"source": [
"Screw_warehouse = {\n",
"\"M5\": 12,\n",
"\"M3\": 0,\n",
"\"M2.5\": 6,\n",
"\"M2\": 20,\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "1b33ffc5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"in stock\n"
]
}
],
"source": [
"\n",
"def Screw_warehouse_manager(screw):\n",
" if screw in Screw_warehouse:\n",
" if Screw_warehouse[screw] > 0:\n",
" return \"in stock\"\n",
" else:\n",
" return \"out of stock\"\n",
" else: \n",
" return \"This screw does not exist\"\n",
" \n",
"\n",
"print(Screw_warehouse_manager(input(\"Screw Name\")))\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "0fbb59ec",
"metadata": {},
"source": [
"### 2.5 Output of component information from a BOM\n",
"Given a BOM with various machine elements, write a Python script that outputs the component information in the following form\n",
"\n",
"The component _______ has the specification: ______ and is made of ________.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "6a7edd07",
"metadata": {},
"outputs": [],
"source": [
"bom_list = [\n",
" [\"Screw\", \"M6x30\", \"42CrMo4\"],\n",
" [\"Nut\", \"M6\", \"42CrMo4\"],\n",
" [\"Washer\", \"M6\", \"Galvanised steel\"],\n",
" [\"Bearing\", \"6204\", \"1.3505\"],\n",
" [\"Shaft\", \"Ø20x1000\", \"C45\"],\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a61db0cf",
"metadata": {},
"outputs": [],
"source": [
"for list in bom_list:\n",
" print(\"The component\", list[0], \"has the specification:\", list[1], \"and is made of\", list[2], \".\")"
]
},
{
"cell_type": "markdown",
"id": "5fbc12e7",
"metadata": {},
"source": [
"Now solve the same exercise this time with a dictionary <br>\n",
"**TIP:** With the ``.items()`` method you can access the key and the value of the dictionary at the same time"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "758e3e09",
"metadata": {},
"outputs": [],
"source": [
"\n",
"bom_dict = {\n",
" \"Screw\": [\"M6x30\", \"42CrMo4\"],\n",
" \"Nut\": [\"M6\", \"42CrMo4\"],\n",
" \"Washer\": [\"M6\", \"Stahl verzinkt\"],\n",
" \"Bearing\": [\"6204\", \"1.3505\"],\n",
" \"Shaft\": [\"Ø20x1000\", \"C45\"],\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9388a373",
"metadata": {},
"outputs": [],
"source": [
"for component_type, (specification, material) in bom_dict.items():\n",
" print(\"The component\", component_type, \"has the specification:\", specification, \"and is made of\", material, \".\")"
]
},
{
"cell_type": "markdown",
"id": "3919aa62",
"metadata": {},
"source": [
"### 2.6 Extract all numbers from a nested list into a single list\n",
"\n",
"In this task, you are to write a Python script that extracts all numbers from a given matrix and saves them in a single list. <br>\n",
"**TIP**: additional elements can be added to a list with extend \n",
"```python\n",
"list.extend(element)\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "ddf65af1",
"metadata": {},
"outputs": [],
"source": [
"matrix = [\n",
"[1, 2, 3, 4, 5, 6],\n",
"[10, 20, 30, 40, 50, 60],\n",
"[100, 200, 300, 400, 500, 600],\n",
"]\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "543433f2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Extracted numbers: [1, 2, 3, 4, 5, 6, 10, 20, 30, 40, 50, 60, 100, 200, 300, 400, 500, 600]\n"
]
}
],
"source": [
"extracted_numbers = []\n",
"\n",
"# Loop through each sublist in the matrix and extend the extracted_numbers list\n",
"for sublist in matrix:\n",
" extracted_numbers.extend(sublist)\n",
"\n",
"# Print the final list of extracted numbers\n",
"print(\"Extracted numbers:\", extracted_numbers)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.12.0"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
%% Cell type:markdown id:41ad2b77 tags:
### 1.1 Namespace basic
Create a function that contains a nested function.
For each space (Global, outer-, and inner Function) define the variable a with different values e.g., 1,2,3
<br>
Show how the namespaces are separated from each other by using the print function in different spaces.
call the outer function
``outer_function``
and the inner function
``inner_function``
%% Cell type:code id:aa5b4c1f tags:
```
python
# global
a
=
1
def
outer_function
():
# outer function
a
=
2
def
inner_function
():
# inner function
a
=
3
print
(
f
"
Inner function scope
'
a
'
=
{
a
}
"
)
# This will print the inner scope variable 'a'
inner_function
()
print
(
f
"
Outer function scope
'
a
'
=
{
a
}
"
)
# This will print the outer scope variable 'a'
# Call the outer function
outer_function
()
# Print the global scope variable 'a'
print
(
f
"
Global scope
'
a
'
=
{
a
}
"
)
```
%% Output
Inner function scope 'a' = 3
Outer function scope 'a' = 2
Global scope 'a' = 1
%% Cell type:markdown id:0a1c4f0d tags:
1.
2 Namespace using
``global``
and
``nonlocal``
%% Cell type:markdown id:ad3e2e48 tags:
### 2.1 Declaration of data collections
Create variables with basic data types with the following names, which can store the corresponding value:
-
the verbs swim run dance
-
The GPS coordinates: 47.2286, 8.8317
-
The definition of a person with name, age, canton of residence
%% Cell type:code id:9f98d24d tags:
```
python
#list to store the verbs: swim, run, dance
verbs
=
[
"
swim
"
,
"
run
"
,
"
dance
"
]
#tuple to store the GPS coordinates (latitude, longitude)
gps_coordinates
=
(
47.2286
,
8.8317
)
# A dictionary to store a definition
person
=
{
"
name
"
:
"
John Doe
"
,
"
age
"
:
30
,
"
canton
"
:
"
St. Gallen
"
}
# Display the variables
print
(
"
Verbs:
"
,
verbs
)
print
(
"
GPS Coordinates:
"
,
gps_coordinates
)
print
(
"
Person:
"
,
person
)
```
%% Output
Verbs: ['swim', 'run', 'dance']
GPS Coordinates: (47.2286, 8.8317)
Person: {'name': 'John Doe', 'age': 30, 'canton': 'St. Gallen'}
%% Cell type:code id:b01c0156 tags:
```
python
# Initial
student
=
{
"
name
"
:
"
Anna
"
,
"
age
"
:
22
,
"
major
"
:
"
social work
"
}
# Add the key "graduation_year"
student
[
"
graduation_year
"
]
=
2025
# Remove the "age" key
student
.
pop
(
"
name
"
)
# Print the updated dictionary
print
(
"
Updated student dictionary:
"
,
student
)
```
%% Output
Updated student dictionary: {'age': 22, 'major': 'social work', 'graduation_year': 2025}
%% Cell type:markdown id:93970c5b tags:
### 2.3 Loop Through a Dictionary
Given the dictionary:
```
python
movie
=
{
x
"
title
"
:
"
Inception
"
,
"
director
"
:
"
Christopher Nolan
"
,
"
release_year
"
:
2010
}
```
Write a Python program that loops through the dictionary and prints both the keys and their corresponding values.
%% Cell type:code id:61004b7b tags:
```
python
movie
=
{
"
title
"
:
"
Inception
"
,
"
director
"
:
"
Christopher Nolan
"
,
"
release_year
"
:
2010
}
# Loop through the dictionary and print both keys and values
for
key
,
value
in
movie
.
items
():
print
(
f
"
{
key
}
:
{
value
}
"
)
```
%% Output
title: Inception
director: Christopher Nolan
release_year: 2010
%% Cell type:markdown id:6b25596c tags:
### 2.4 Checking the availability of screws in the warehouse
Define a
``screw_warehouse_manager``
function that checks whether a particular screw exists in the warehouse and whether it is in stock.
### Task
1.
**Dictionary**
-
Given is a dictionary 'screw warehouse' that contains different screw types and their available quantities.
2.
**Implement function**
-
Implement the function
`Screw_warehouse_manager(screw)`
, which performs the following checks:
-
If the screw is available in stock and the quantity is greater than 0, the function returns
`“in stock”`
.
-
If the screw is in stock but the quantity is 0, the function returns “out of stock”.
-
If the screw is not in stock, the function returns
`“does not exist”`
.
%% Cell type:code id:149d200c tags:
```
python
Screw_warehouse
=
{
"
M5
"
:
12
,
"
M3
"
:
0
,
"
M2.5
"
:
6
,
"
M2
"
:
20
,
}
```
%% Cell type:code id:1b33ffc5 tags:
```
python
def
Screw_warehouse_manager
(
screw
):
if
screw
in
Screw_warehouse
:
if
Screw_warehouse
[
screw
]
>
0
:
return
"
in stock
"
else
:
return
"
out of stock
"
else
:
return
"
This screw does not exist
"
print
(
Screw_warehouse_manager
(
input
(
"
Screw Name
"
)))
```
%% Output
in stock
%% Cell type:markdown id:0fbb59ec tags:
### 2.5 Output of component information from a BOM
Given a BOM with various machine elements, write a Python script that outputs the component information in the following form
The component _______ has the specification: ______ and is made of ________.
%% Cell type:code id:6a7edd07 tags:
```
python
bom_list
=
[
[
"
Screw
"
,
"
M6x30
"
,
"
42CrMo4
"
],
[
"
Nut
"
,
"
M6
"
,
"
42CrMo4
"
],
[
"
Washer
"
,
"
M6
"
,
"
Galvanised steel
"
],
[
"
Bearing
"
,
"
6204
"
,
"
1.3505
"
],
[
"
Shaft
"
,
"
Ø20x1000
"
,
"
C45
"
],
]
```
%% Cell type:code id:a61db0cf tags:
```
python
for
list
in
bom_list
:
print
(
"
The component
"
,
list
[
0
],
"
has the specification:
"
,
list
[
1
],
"
and is made of
"
,
list
[
2
],
"
.
"
)
```
%% Cell type:markdown id:5fbc12e7 tags:
Now solve the same exercise this time with a dictionary
<br>
**TIP:**
With the
``.items()``
method you can access the key and the value of the dictionary at the same time
%% Cell type:code id:758e3e09 tags:
```
python
bom_dict
=
{
"
Screw
"
:
[
"
M6x30
"
,
"
42CrMo4
"
],
"
Nut
"
:
[
"
M6
"
,
"
42CrMo4
"
],
"
Washer
"
:
[
"
M6
"
,
"
Stahl verzinkt
"
],
"
Bearing
"
:
[
"
6204
"
,
"
1.3505
"
],
"
Shaft
"
:
[
"
Ø20x1000
"
,
"
C45
"
],
}
```
%% Cell type:code id:9388a373 tags:
```
python
for
component_type
,
(
specification
,
material
)
in
bom_dict
.
items
():
print
(
"
The component
"
,
component_type
,
"
has the specification:
"
,
specification
,
"
and is made of
"
,
material
,
"
.
"
)
```
%% Cell type:markdown id:3919aa62 tags:
### 2.6 Extract all numbers from a nested list into a single list
In this task, you are to write a Python script that extracts all numbers from a given matrix and saves them in a single list.
<br>
**TIP**
: additional elements can be added to a list with extend
```
python
list
.
extend
(
element
)
%%
Cell
type
:
code
id
:
ddf65af1
tags
:
```
python
matrix = [
[1, 2, 3, 4, 5, 6],
[10, 20, 30, 40, 50, 60],
[100, 200, 300, 400, 500, 600],
]
```
%% Cell type:code id:543433f2 tags:
```
python
extracted_numbers = []
# Loop through each sublist in the matrix and extend the extracted_numbers list
for sublist in matrix:
extracted_numbers.extend(sublist)
# Print the final list of extracted numbers
print("Extracted numbers:", extracted_numbers)
```
%% Output
Extracted numbers: [1, 2, 3, 4, 5, 6, 10, 20, 30, 40, 50, 60, 100, 200, 300, 400, 500, 600]
This diff is collapsed.
Click to expand it.
unit-5/JSON example/employeesheet.json
0 → 100644
+
39
−
0
View file @
f5b9aed7
{
"store"
:
{
"name"
:
"TechGadget Online"
,
"location"
:
"San Francisco"
,
"currency"
:
"USD"
},
"products"
:
[
{
"id"
:
101
,
"name"
:
"Wireless Mouse"
,
"brand"
:
"LogiTech"
,
"price"
:
29.99
,
"stock"
:
150
,
"categories"
:
[
"Electronics"
,
"Accessories"
],
"rating"
:
4.7
,
"available"
:
true
},
{
"id"
:
102
,
"name"
:
"Bluetooth Speaker"
,
"brand"
:
"JBL"
,
"price"
:
89.99
,
"stock"
:
85
,
"categories"
:
[
"Electronics"
,
"Audio"
],
"rating"
:
4.5
,
"available"
:
true
},
{
"id"
:
103
,
"name"
:
"Gaming Keyboard"
,
"brand"
:
"Razer"
,
"price"
:
119.99
,
"stock"
:
45
,
"categories"
:
[
"Electronics"
,
"Accessories"
],
"rating"
:
4.8
,
"available"
:
false
}
]
}
\ No newline at end of file
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment