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

made some minot adjustments

parent a7e5f3f7
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:becc5c8b tags:
# Week 4: Applying previous knowledge to Python
## Control structures II
# Week 4: Control Strucutres
%% Cell type:markdown id:0e3d6582 tags:
## 1. for loops
%% Cell type:markdown id:b1521cf0 tags:
#### 2.2.1 Ausgabe einer Liste
Given a list of animals. Write a program that outputs the contents of the list
%% Cell type:code id:9d700e0f tags:
``` python
animals = ['dog', 'cat', 'bird', 'fish']
```
%% Cell type:code id:a27c48de tags:
``` python
for single_animal in animals:
print(single_animal)
```
%% Output
dog
cat
bird
fish
%% Cell type:markdown id:f00bbc4f tags:
#### 2.2.2 Determine the data types of list elements
Given a list with data, extend the code so that the data types of the individual variables are listed in a new list called ``type_list``
Output the newly created list with a print command
%% Cell type:code id:046a9e3f tags:
``` python
List = [ 3.1, "Hallo Welt", True]
```
%% Cell type:code id:693fca94 tags:
``` python
type_list = []
for x in List:
type_list.append(type(x))
print(type_list)
```
%% Output
[<class 'float'>, <class 'str'>, <class 'bool'>]
%% Cell type:code id:542fbf4e tags:
``` python
type_list = [type(x) for x in List]
print(type_list)
```
%% Output
[<class 'float'>, <class 'str'>, <class 'bool'>]
%% Cell type:markdown id:800d6106 tags:
#### 2.2.3 Primzahl ermittlung
Write a program that checks whether a given number is a prime number. <br>
Tip: **int()** can be used to convert values into integers
**Logik** A prime number is a natural number which is greater than 1 and is only divisible by itself and by 1 without remainder. <br>
**TIP:** Use the function ``range(start, stop, step)`` to generate divisors to be checked.<br>
for that the ``break`` statement can be used
%% Cell type:code id:948bddc1 tags:
``` python
n = 8
if n <= 1:
print("The number is not a prime number")
else:
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
print("The number is not a prime number.")
break
else:
print("The number is a prime number")
```
%% Output
Die Zahl ist keine Primzahl.
%% Cell type:markdown id:259d8ec3 tags:
### 2.3 Advanced tasks
%% Cell type:markdown id:3c5b5e51 tags:
### 2.3.1 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
Schraubenlager = {
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 Schraubenlager:
if Schraubenlager[screw] > 0:
return "in stock"
else:
return "out of stock"
else:
return "does not exist"
screw = input("What screw needs to be checked")
result = Screw_warehouse_manager(screw)
print(result) # Ausgabe: "in stock"
```
%% Output
out of stock
%% Cell type:markdown id:53685910 tags:
#### 2.3.1 Palindrome checker
Write a program to check whether a word is a palindrome.
A palindrome is a word, a sentence, a number or another sequence of characters that can be read the same forwards and backwards.
**TIP** with the slicing syntax [::-1], a string can be reversed <br>
You can use the ``.lower()`` function to ignore upper and lower case letters
%% Cell type:code id:c25c88c9 tags:
``` python
def is_palindrom(word):
word = word.lower()
if word == word[::-1]:
return("palindrom")
else:
return("no palindrom")
wort = "Anna"
is_palindrom(input("Wort"))
```
%% Output
'no palindrom'
%% Cell type:code id:f1ac2043 tags:
``` python
def is_palindrom(word):
word = word.lower()
x = 0
for buchstaben in wort:
if wort[-(1+x)] == wort[0+x]:
x += 1
else:
return("no palindrom")
break
if len(wort) == x:
return("palindrom")
word = "Anna"
result = is_palindrom(input("Wort"))
print(result)
```
%% Output
no palindrom
%% Cell type:markdown id:ec6bf765 tags:
#### 2.3.2 Fibonacci
Schreiben Sie eine Funktion namens fibonacci, die eine Zahl n als Parameter nimmt und die ersten n Zahlen der Fibonacci-Folge in einer Liste zurückgibt.
Hinweise zur Implementierung:
Die Fibonacci-Folge beginnt mit 0 und 1. Jede weitere Zahl ist die Summe der beiden vorhergehenden Zahlen.
Verwenden Sie eine Schleife, um die Zahlenfolge zu erzeugen.
> start with ``fibonacci = [0,1]`` to make programming easier
%% Cell type:code id:6807e28c tags:
``` python
def fibonacci(n):
fibonacci = [0,1]
for i in range(2, n):
fibonacci.append(fibonacci[i-1]+fibonacci[i-2])
return fibonacci
List = []
List = fibonacci(6)
print(List)
```
%% Output
[0, 1, 1, 2, 3, 5]
%% Cell type:markdown id:21082eed tags:
#### 2.3.3 Sum of the digits
#### 2.3.3 Sum of digits
Task:
Write a function called sum_of_digits that takes an integer as a parameter and returns the sum of its digits.
Implementation notes:
You can convert the number to a string to extract each digit, or use math operations to isolate the digits.
%% Cell type:code id:e8b74bc6 tags:
``` python
def sum_of_digit(n):
value = 0
numberstr = str(n)
for number in numberstr:
value += int(number)
return value
sum_of_digit(input("what number?"))
```
%% Output
15
%% Cell type:code id:4f5ef8d0 tags:
``` python
def sum_of_digits(n):
n = str(n)
summe = 0
for digit in n:
summe = summe + int(digit)
return summe
print(sum_of_digits(55))
```
%% Output
10
%% Cell type:markdown id:77c5124c tags:
#### 2.3.4 Faculty calculation
- Write a function called factorial that takes a number n as a parameter and returns the factorial of this number.
- **Logic** The factorial of a number n is the product of all positive integers less than or equal to n.
> **TIP:** Use a for loop to calculate the product
%% Cell type:code id:73694875 tags:
``` python
def factorial(n):
prod = 1
for i in range(n):
prod = prod*(i+1)
return prod
print(factorial(3))
```
%% Output
6
%% Cell type:code id:e7ed38d9 tags:
``` python
def Fakultät(n):
fak = 1
for i in range(1,n+1):
fak = fak * i
return fak
print(Fakultät(3))
```
%% Output
6
%% Cell type:markdown id:a15c9045 tags:
#### 2.3.5 Anzahl der Vokale in einem String
Ziel: Schreiben Sie eine Funktion count_vowels, die einen String als Parameter nimmt und die Anzahl der Vokale im String zurückgibt.
#### 2.3.5 Number of vowels in a string
Write a function ``count_vowels`` that takes a string as a parameter and returns the number of vowels in the string.
> **TIP:** You can use ``.lower()`` to make the function case-insensitive, ensuring it counts both uppercase and lowercase vowels.
%% Cell type:code id:e7754f7b tags:
``` python
def count_vowels(word):
n_vowels = 0
word = word.lower()
vowels= "aeiou"
for letter in word:
if letter in vowels:
n_vowels += 1
return n_vowels
print(count_vowels("ooooO"))
```
%% Output
5
%% Cell type:markdown id:5abd2d86 tags:
#### 2.3.2 Bubblesort algarythm: **for Geeks!**
Bubblesort algarythmus:
Write a function called bubble_sort that takes a list of numbers as parameters.
Implement algorithm:
Inside the function, use the bubble sort algorithm to sort the list.
The algorithm should compare and swap neighboring elements until the entire list is sorted.
Test:
Test the function with multiple lists of numbers to make sure it sorts correctly.
Implementation notes:
Bubble Sort Logic: start at the beginning of the list and compare each neighboring pair of elements. Swap the elements if the first element is greater than the second. Repeat this process for each pairing in the list, then start again from the beginning until a run without swaps has been completed.
Optimization option: You can use a variable to track whether swaps have been made. If a complete run ends without swaps, you can end the sorting as the list is already sorted.
test_array = [64, 34, 25, 12, 22, 11, 90]
%% Cell type:code id:b0ef1b7b tags:
``` python
test_array = [64, 13, 34, 33, 69, 55, 25, 11, 90, 73, 288]
list_sorted = []
def bubblesort(list):
print(list)
n = len(list)
for i in range(n):
for j in range(n-1-i):
if list[j] > list[j+1]:
list[j],list[j+1] = list[j+1],list[j]
return list
list_sorted = bubblesort(test_array)
print(list_sorted)
```
%% Cell type:code id:15039a4e tags:
``` python
test_array = [64, 13, 34, 33, 69, 55, 25, 11, 90, 73, 288]
n = len(test_array)
print(n)
for i in range(n):
swapped = False
for j in range(n-1-i):
if test_array[j] > test_array[j+1]:
test_array[j], test_array[j+1] = test_array[j+1], test_array[j]
swapped = True
if not swapped:
break
print(test_array)
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment