Skip to content
Snippets Groups Projects
Commit d8960070 authored by Jöran Frey's avatar Jöran Frey
Browse files

added content

parent e91dcc12
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:472674d0 tags:
# Exercise 11: Week 13
## Mixed tasks recap
%% Cell type:markdown id:39c985b1 tags:
## mixed tasks
## 1.1 loops
## 1 loops
### 1.1 While loop
### 1.1.1 While loop
Output the numbers from 1-9 with a While loop
%% Cell type:code id:4963b926 tags:
``` python
i = 0
while i < 9:
i += 1
print(i)
```
%% Cell type:markdown id:5e94ba89 tags:
Write a function that uses a while loop to calculate the sum of numbers from 1 to n, where n is input by the user.
%% Cell type:code id:6d7d3a25 tags:
``` python
```
%% Output
3
%% Cell type:markdown id:8a698b41 tags:
### 1.1.2 for loop
Write a function that calculates the sum of all numbers in a list provided by the user.
%% Cell type:code id:2ccbb033 tags:
``` python
```
%% Output
137
%% Cell type:markdown id:ba627a5b tags:
### 1.2 Use list comprehensions to solve the following tasks:
- Create an array that contains all squares of the numbers from 0 to 100
contains.
- Create an array containing all numbers from 0 to 1000 that are not divisible by divisible by 11 and not divisible by 13.
- Create an array of length 100 that contains zeros at all even index positionspositions and ones at all odd index positions.
%% Cell type:code id:658e78ea tags:
``` python
squares = [x**2 for x in range(0,101)]
print(squares)
x = 0
ndivisable = [y for y in range(0,1001) if ((y % 11 != 0) and (y % 13 != 0))]
print(ndivisable)
evenodd = [0 if (z % 2 !=0) else 1 for z in range(0,101)]
print(evenodd)
```
%% Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916, 3025, 3136, 3249, 3364, 3481, 3600, 3721, 3844, 3969, 4096, 4225, 4356, 4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241, 6400, 6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921, 8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409, 9604, 9801, 10000]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 92, 93, 94, 95, 96, 97, 98, 100, 101, 102, 103, 105, 106, 107, 108, 109, 111, 112, 113, 114, 115, 116, 118, 119, 120, 122, 123, 124, 125, 126, 127, 128, 129, 131, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 157, 158, 159, 160, 161, 162, 163, 164, 166, 167, 168, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 181, 183, 184, 185, 186, 188, 189, 190, 191, 192, 193, 194, 196, 197, 199, 200, 201, 202, 203, 204, 205, 206, 207, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 222, 223, 224, 225, 226, 227, 228, 229, 230, 232, 233, 235, 236, 237, 238, 239, 240, 241, 243, 244, 245, 246, 248, 249, 250, 251, 252, 254, 255, 256, 257, 258, 259, 261, 262, 263, 265, 266, 267, 268, 269, 270, 271, 272, 274, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 298, 300, 301, 302, 303, 304, 305, 306, 307, 309, 310, 311, 313, 314, 315, 316, 317, 318, 320, 321, 322, 323, 324, 326, 327, 328, 329, 331, 332, 333, 334, 335, 336, 337, 339, 340, 342, 343, 344, 345, 346, 347, 348, 349, 350, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 365, 366, 367, 368, 369, 370, 371, 372, 373, 375, 376, 378, 379, 380, 381, 382, 383, 384, 386, 387, 388, 389, 391, 392, 393, 394, 395, 397, 398, 399, 400, 401, 402, 404, 405, 406, 408, 409, 410, 411, 412, 413, 414, 415, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 441, 443, 444, 445, 446, 447, 448, 449, 450, 452, 453, 454, 456, 457, 458, 459, 460, 461, 463, 464, 465, 466, 467, 469, 470, 471, 472, 474, 475, 476, 477, 478, 479, 480, 482, 483, 485, 486, 487, 488, 489, 490, 491, 492, 493, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 508, 509, 510, 511, 512, 513, 514, 515, 516, 518, 519, 521, 522, 523, 524, 525, 526, 527, 529, 530, 531, 532, 534, 535, 536, 537, 538, 540, 541, 542, 543, 544, 545, 547, 548, 549, 551, 552, 553, 554, 555, 556, 557, 558, 560, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 584, 586, 587, 588, 589, 590, 591, 592, 593, 595, 596, 597, 599, 600, 601, 602, 603, 604, 606, 607, 608, 609, 610, 612, 613, 614, 615, 617, 618, 619, 620, 621, 622, 623, 625, 626, 628, 629, 630, 631, 632, 633, 634, 635, 636, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 651, 652, 653, 654, 655, 656, 657, 658, 659, 661, 662, 664, 665, 666, 667, 668, 669, 670, 672, 673, 674, 675, 677, 678, 679, 680, 681, 683, 684, 685, 686, 687, 688, 690, 691, 692, 694, 695, 696, 697, 698, 699, 700, 701, 703, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 727, 729, 730, 731, 732, 733, 734, 735, 736, 738, 739, 740, 742, 743, 744, 745, 746, 747, 749, 750, 751, 752, 753, 755, 756, 757, 758, 760, 761, 762, 763, 764, 765, 766, 768, 769, 771, 772, 773, 774, 775, 776, 777, 778, 779, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 794, 795, 796, 797, 798, 799, 800, 801, 802, 804, 805, 807, 808, 809, 810, 811, 812, 813, 815, 816, 817, 818, 820, 821, 822, 823, 824, 826, 827, 828, 829, 830, 831, 833, 834, 835, 837, 838, 839, 840, 841, 842, 843, 844, 846, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 870, 872, 873, 874, 875, 876, 877, 878, 879, 881, 882, 883, 885, 886, 887, 888, 889, 890, 892, 893, 894, 895, 896, 898, 899, 900, 901, 903, 904, 905, 906, 907, 908, 909, 911, 912, 914, 915, 916, 917, 918, 919, 920, 921, 922, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 937, 938, 939, 940, 941, 942, 943, 944, 945, 947, 948, 950, 951, 952, 953, 954, 955, 956, 958, 959, 960, 961, 963, 964, 965, 966, 967, 969, 970, 971, 972, 973, 974, 976, 977, 978, 980, 981, 982, 983, 984, 985, 986, 987, 989, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000]
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
%% Cell type:markdown id:750b8da3 tags:
%% Cell type:markdown id:0f5a3313 tags:
### 1.3 Input output
Ask the user for their first name, last name, and age.
Calculates the year they were born based on the current year (2024).
Print a message like: "Hello [first name] [last name], you are [age] years old and were born in [year]".
%% Cell type:code id:b0d6532a tags:
``` python
```
# Aufgabe: Temperatur-Kategorisierung und Empfehlungen
%% Cell type:markdown id:750b8da3 tags:
Schreibe ein Python-Programm, das die aktuelle Temperatur in Grad Celsius als Eingabe akzeptiert und anhand dieser verschiedene Aktionen durchführt.
# 1.4 Task: Temperature categorization and recommendations
## Anforderungen
Write a Python program that accepts the current temperature in degrees Celsius as input and performs various actions based on this.
### 1. Eingabe
Fordere den Benutzer auf, die aktuelle Temperatur (in Grad Celsius) einzugeben.
### input
Ask the user to enter the current temperature (in degrees Celsius).
### 2. Kategorien und Aktionen
- **Temperatur < 0**: Gib aus, dass es sehr kalt ist, und empfehle, einen dicken Mantel und Handschuhe zu tragen.
- **0 ≤ Temperatur < 10**: Gib aus, dass es kalt ist, und empfehle, eine Jacke und einen Schal zu tragen.
- **Temperatur ≥ 30**: Gib aus, dass es sehr heiß ist, und empfehle, viel Wasser zu trinken und Sonnenschutz zu verwenden.
### 2. categories and actions
- Temperature < 0**: Indicate that it is very cold and recommend wearing a thick coat and gloves.
- **0 ≤ temperature < 10**: State that it is cold and recommend wearing a jacket and scarf.
- **Temperature ≥ 30**: State that it is very hot and recommend drinking plenty of water and using sunscreen.
### 3. Ungültige Eingaben
Falls der Benutzer etwas anderes als eine Zahl eingibt, soll das Programm eine Fehlermeldung ausgeben und den Benutzer bitten, eine gültige Zahl einzugeben.
die exception kann mit try und except ValueError: programmiert werden
### 3. invalid entries (advanced)
If the user enters something other than a number, the program should display an error message and ask the user to enter a valid number. <br>
The exception can be programmed with try and except ValueError:.
%% Cell type:code id:f7746781 tags:
``` python
def temperatur_kategorisierung():
while True:
try:
# Eingabe der aktuellen Temperatur
temperatur = float(input("Bitte die aktuelle Temperatur in Grad Celsius eingeben: "))
# Kategorien und Aktionen
if temperatur < 0:
print("Es ist sehr kalt. Empfehlung: Tragen Sie einen dicken Mantel und Handschuhe.")
elif 0 <= temperatur < 10:
print("Es ist kalt. Empfehlung: Tragen Sie eine Jacke und einen Schal.")
elif temperatur >= 30:
print("Es ist sehr heiss. Empfehlung: Trinken Sie viel Wasser und verwenden Sie Sonnenschutz.")
else:
print("Das Wetter ist angenehm. Keine besonderen Empfehlungen.")
break # Beende die Schleife nach erfolgreicher Eingabe
except ValueError:
print("Ungültige Eingabe. Bitte geben Sie eine gültige Zahl ein.")
# Programm starten
temperatur_kategorisierung()
```
%% Output
Das Wetter ist angenehm. Keine besonderen Empfehlungen.
%% Cell type:markdown id:3cd42cc9 tags:
%% Cell type:markdown id:4e8fa130 tags:
## 1.5 Check Tic Tac Toe
## Task: Manage a Material Inventory System with pandas
The goal of this task is to check whether someone has WON a game of Tic Tac Toe.
Create a Python program to manage an inventory of materials using nested dictionaries.
Program a function ```check_tictactoe(game)``` which returns whether player 1 or player 2 has won
The Following features should be implemented
**hint:** several lines can be checked for a winner when using a for loop
- **View Inventory:** Display all categories, materials, and their details.
- **Add a New Material:** Add a new material to a category (create a new category if it doesn't exist).
- **Update Material** Quantity: Modify the quantity of an existing material by adding or subtracting a given amount. Ensure the total cannot go below 0.
- **Delete a Material:** Remove a material from the inventory entirely.
- **Exit:** End the program.
%% Cell type:code id:ae0f77dc tags:
``` python
import pandas as pd
# Load inventory from the CSV file
file_path = "Daten/Materials.csv"
inventory = pd.read_csv(file_path)
def view_inventory():
global inventory
print("\nCurrent Inventory:")
print(inventory.to_string())
def add_material():
global inventory
category = input("Enter the category: ")
material = input("Enter the material name: ")
try:
quantity = int(input("Enter the quantity: "))
except ValueError:
print("Invalid quantity. Please enter a number.")
return
unit = input("Enter the unit: ")
new_entry = {"Category": category, "Material": material, "Quantity": quantity, "Unit": unit}
inventory = pd.concat([inventory, pd.DataFrame([new_entry])], ignore_index=True)
print(f"Material '{material}' added to category '{category}'.")
def update_material():
global inventory
material = input("Enter the material name to update: ")
if material not in inventory["Material"].values:
print(f"Material '{material}' not found in inventory.")
return
try:
quantity_change = int(input("Enter the quantity change (positive or negative): "))
except ValueError:
print("Invalid quantity. Please enter a number.")
return
inventory.loc[inventory["Material"] == material, "Quantity"] += quantity_change
# Ensure quantity doesn't go below 0
inventory["Quantity"] = inventory["Quantity"].clip(lower=0)
print(f"Material '{material}' updated.")
def delete_material():
global inventory
material = input("Enter the material name to delete: ")
if material in inventory["Material"].values:
inventory = inventory[inventory["Material"] != material]
print(f"Material '{material}' deleted.")
else:
print(f"Material '{material}' not found.")
def main():
while True:
print("\nMaterial Inventory System")
print("1. View Inventory")
print("2. Add a New Material")
print("3. Update Material Quantity")
print("4. Delete a Material")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
view_inventory()
elif choice == "2":
add_material()
elif choice == "3":
update_material()
elif choice == "4":
delete_material()
elif choice == "5":
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
main()
<img src="data/image.png" alt="Alt Text" width="300"/>
%% Cell type:code id:a9a7b16f tags:
``` python
#example games
winner_is_2 = [[2, 2, 0],
[2, 1, 0],
[2, 1, 1]]
winner_is_1 = [[1, 2, 0],
[2, 1, 0],
[2, 1, 1]]
winner_is_also_1 = [[0, 1, 0],
[2, 1, 0],
[2, 1, 1]]
no_winner = [[1, 2, 0],
[2, 1, 0],
[2, 1, 2]]
also_no_winner = [[1, 2, 0],
[2, 1, 0],
[2, 1, 0]]
```
%% Cell type:code id:748a40d6 tags:
``` python
```
%% Cell type:markdown id:f6be9554 tags:
## 1.6 Number guessing
Write a Python program for a number-guessing game. The program should allow the user to attempt guessing a secret number up to 5 times. If the user guesses the correct number, the program should display a success message and stop. If the user fails to guess correctly within 5 attempts, it should display the correct number and a failure message.
The range of the Random number should be between 1 and 25
%% Cell type:code id:c176ee1b tags:
``` python
```
%% Output
Try to guess the number between 1 and 25. You have 5 attempts.
Invalid input. Please enter a valid number.
None
%% Cell type:markdown id:b6a24fe8 tags:
## 1.7 Pandas
Pokémon data analysis (again)
1. load data:
Load the data set into a Pandas DataFrame.
2. basic analysis:
- How many Pokémon are there in total in the data set?
- How many different Pokémon types are there (including type 1 and type 2)? (**hint** use the ```unique()``` method to find all unique pokemons)(use the ```concat()``` method to concatenate the calues from multiple Series into a single serie)
List all unique types.
3. filtering and grouping:
- Find the strongest Pokémon (highest total value).
- Find the fastest Pokémon (highest speed value).
- Create a ranking list of the 5 legendary Pokémon with the highest total value.
4. visualisation:
- Create a bar chart showing the average values (total) of the Pokémon per generation.
%% Cell type:code id:e527fa96 tags:
``` python
```
%% Output
There are 800 pokémons
Material Inventory System
1. View Inventory
2. Add a New Material
3. Update Material Quantity
4. Delete a Material
5. Exit
Current Inventory:
Category Material Quantity Unit
0 Metals Steel 500 kg
1 Metals Aluminum 300 kg
2 Metals Copper 150 kg
3 Metals Titanium 50 kg
4 Polymers Polyethylene 1000 m³
5 Polymers PVC 600 m³
6 Polymers Polycarbonate 200 m³
7 Polymers Nylon 400 kg
8 Ceramics Porcelain 200 pieces
9 Ceramics Silicon Carbide 80 kg
10 Ceramics Zirconia 150 kg
11 Ceramics Alumina 300 kg
12 Composites Carbon Fiber 50 m³
13 Composites Glass Fiber 100 m³
14 Composites Kevlar 30 rolls
15 Composites Epoxy Resin 250 liters
16 Wood Oak 1000 m³
17 Wood Pine 800 m³
18 Wood Birch 600 m³
19 Wood Teak 400 m³
There are 19 types of pokémons
Material Inventory System
1. View Inventory
2. Add a New Material
3. Update Material Quantity
4. Delete a Material
5. Exit
Invalid choice. Please try again.
Material Inventory System
1. View Inventory
2. Add a New Material
3. Update Material Quantity
4. Delete a Material
5. Exit
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
Cell In[28], line 79
77 else:
78 print("Invalid choice. Please try again.")
---> 79 main()
Cell In[28], line 65, in main()
62 print("4. Delete a Material")
63 print("5. Exit")
---> 65 choice = input("Enter your choice: ")
66 if choice == "1":
67 view_inventory()
File ~\AppData\Roaming\Python\Python312\site-packages\ipykernel\kernelbase.py:1282, in Kernel.raw_input(self, prompt)
1280 msg = "raw_input was called, but this frontend does not support input requests."
1281 raise StdinNotImplementedError(msg)
-> 1282 return self._input_request(
1283 str(prompt),
1284 self._parent_ident["shell"],
1285 self.get_parent("shell"),
1286 password=False,
1287 )
File ~\AppData\Roaming\Python\Python312\site-packages\ipykernel\kernelbase.py:1325, in Kernel._input_request(self, prompt, ident, parent, password)
1322 except KeyboardInterrupt:
1323 # re-raise KeyboardInterrupt, to truncate traceback
1324 msg = "Interrupted by user"
-> 1325 raise KeyboardInterrupt(msg) from None
1326 except Exception:
1327 self.log.warning("Invalid Message:", exc_info=True)
KeyboardInterrupt: Interrupted by user
The Fastest Pokemon is DeoxysSpeed Forme
The strongest Pokemon is MewtwoMega Mewtwo X
Top 5 legendary poekmons ranked
163 MewtwoMega Mewtwo X
164 MewtwoMega Mewtwo Y
426 RayquazaMega Rayquaza
422 KyogrePrimal Kyogre
424 GroudonPrimal Groudon
Name: Name, dtype: object
%% Cell type:markdown id:f1846f3a tags:
## 1.8 Dicionary
Given is a dicionary with different materials and their parameters.
- Identify which material has the highest density and display its name and properties.
- Identify materials with "Vehicles" as one of their applications.
%% Cell type:code id:14a6189d tags:
``` python
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment