Commit cbef1e07 authored by christian.foerster's avatar christian.foerster

update

parent 0040f636
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -6,12 +6,39 @@
"source": [
"# A short Introdcution to Python\n",
"\n",
"## Things you might be wondering:\n",
"- What is an Anaconda and what does it have to do with Python\n",
" - Anaconda program to manage virtual environments\n",
" - can be set up in a virtual environment\n",
" \n",
" \n",
"- Python 2 vs Python 3?\n",
" - unsupported vs. supported\n",
" \n",
" \n",
"- Where does Python fit in? \n",
" - for educational purposes (https://www.researchgate.net/publication/328175547_MatLab_vs_Python_vs_R)\n",
" - more generally speaking (https://pyzo.org/python_vs_matlab.html) (R is out mainly for data wrangling)\n",
" - development -> if you want to develop open source software, that many people can use, you need a open source language!\n",
" \n",
" \n",
"- Is Python fast?\n",
" - not really\n",
" - it can comparable to c++/c/fortran (numpy, cython, numba)\n",
" \n",
" \n",
"- Why is Python so popular?\n",
" - easy to learn/use\n",
" - code readabiltiy \n",
" - open source \n",
" - huge commuinuty\n",
" - general purpose language\n",
"\n",
"## Some nice-to-know's\n",
"* indexing starts at 0\n",
"* the syntax i controlled mainly by tabs (4 spaces), that mean less brackets and better readability\n",
" * so you should adapt your texteditor (e.g.: notepad++) to replace a tab with 4 spaces\n",
"* commet with hashtag, multiline comments/docstrings like so \"\"\"my comment or docstring\"\"\""
"* commet with hashtag, multiline comments/docstrings like so \"\"\"my comment or docstring\"\"\"\n"
]
},
{
......@@ -23,7 +50,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 3,
"metadata": {},
"outputs": [
{
......@@ -43,7 +70,7 @@
"25"
]
},
"execution_count": 1,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
......@@ -881,6 +908,21 @@
"[(True,i) if i%2==0 else (False,i) for i in range(29)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Learning by doing!\n",
"### Task 1\n",
"\n",
"In order to not fall asleep when looking at the python syntax, we'll try to do so with a little task in mind!\n",
"Lets write a little program which can be used to analyse files and can count the occurance of patterns in each line!\n",
"\n",
"__Pattern Analyser__\n",
" - input: A string! (later a file)\n",
" - output: Number of occurances in each line!\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -953,7 +995,7 @@
},
{
"cell_type": "code",
"execution_count": 71,
"execution_count": 2,
"metadata": {},
"outputs": [
{
......@@ -962,14 +1004,15 @@
"3000"
]
},
"execution_count": 71,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import sys\n",
"sys.getrecursionlimit()"
"sys.getrecursionlimit()\n",
"#sys.setrecursionlimit()"
]
},
{
......@@ -1022,7 +1065,7 @@
"%timeit factorial_fast(2000)\n",
"%timeit factorial_fastest(2000)\n",
"\n",
"# for is faster than while"
"# for is faster than while\n"
]
},
{
......@@ -3047,13 +3090,98 @@
"## Object Oriented Programming"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4 Pillars of OOP\n",
"- Inheritance (a way to reuse your code)\n",
"- Abstraction (showing only essential features hiding details)\n",
"- Encapsulation (bind data variables and functions together in a class)\n",
"- Polymorphism (create functions with same name and different arguments, redefine functions)"
]
},
{
"cell_type": "code",
"execution_count": 132,
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# Parent class\n",
"class Dog:\n",
" # Class attribute\n",
" species = 'mammal'\n",
"\n",
" # Initializer / Instance attributes\n",
" def __init__(self, name, age):\n",
" self.name = name\n",
" self.age = age\n",
"\n",
" # instance method\n",
" def description(self):\n",
" return \"{} is {} years old\".format(self.name, self.age)\n",
"\n",
" # instance method\n",
" def speak(self, sound):\n",
" return \"{} says {}\".format(self.name, sound)\n",
"\n",
" \n",
"# Child class (inherits from Dog() class)\n",
"class RussellTerrier(Dog):\n",
" def run(self, speed):\n",
" return \"{} runs {}\".format(self.name, speed)\n",
"\n",
"\n",
"# Child class (inherits from Dog() class)\n",
"class Bulldog(Dog):\n",
" def run(self, speed):\n",
" return \"{} runs {}\".format(self.name, speed)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Child classes inherit attributes and\n",
"# behaviors from the parent class\n",
"jim = Bulldog(\"Jim\", 12)\n",
"print(jim.description())\n",
"\n",
"# Child classes have specific attributes\n",
"# and behaviors as well\n",
"print(jim.run(\"slowly\"))\n",
"\n",
"# Is jim an instance of Dog()?\n",
"print(isinstance(jim, Dog))\n",
"\n",
"# Is julie an instance of Dog()?\n",
"julie = Dog(\"Julie\", 100)\n",
"print(isinstance(julie, Dog))\n",
"\n",
"# Is johnny walker an instance of Bulldog()\n",
"johnnywalker = RussellTerrier(\"Johnny Walker\", 4)\n",
"print(isinstance(johnnywalker, Bulldog))\n",
"\n",
"# Is julie and instance of jim?\n",
"print(isinstance(julie, RussellTerrier))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Special Methods, hidden Variables, ...\n",
"Fancy things we can do!"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# thats how you define a class\n",
"class Bank_Account():\n",
" bank = \"Some Bank\"\n",
" '''my documentation'''\n",
......@@ -3095,7 +3223,7 @@
},
{
"cell_type": "code",
"execution_count": 133,
"execution_count": 3,
"metadata": {},
"outputs": [
{
......@@ -3111,7 +3239,7 @@
"667"
]
},
"execution_count": 133,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
......@@ -3126,30 +3254,6 @@
"Jana+Steffen"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 134,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is an instance of the class Bank_Account.\n"
]
}
],
"source": [
"repr()"
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -3233,6 +3337,67 @@
"So jetzt zeigen ich einfach mal ein paar Beispiele und die kannst du ja mal nachvollziehen. Danach bekommst du ein paar Übungsaufgaben."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Notepad():\n",
" def __init__(self):\n",
" self.notes = {}\n",
" self.selectedNote=None\n",
" return\n",
" \n",
" def _noteNameCheck(self,noteName):\n",
" if noteName is None and self.selectedNote is None:\n",
" raise ValueError(\"Please provide a noteName.\")\n",
" elif noteName is None:\n",
" noteName = self.selectedNote\n",
" return noteName\n",
" \n",
" def addNote(self, noteName):\n",
" self.selectedNote=noteName\n",
" self.notes[noteName] = {}\n",
" return self.notes\n",
" \n",
" def deleteNote(self, noteName=None):\n",
" noteName = self._noteNameCheck(noteName)\n",
" del self.notes[noteName]\n",
" self.selectedNote = None \n",
" return self.notes\n",
" \n",
" def addEntry(self, entry, noteName=None):\n",
" noteName = self._noteNameCheck(noteName)\n",
" self.notes[noteName][entry]=\"unmarked\"\n",
" return self.notes\n",
" \n",
" def deleteEntry(self, entry, noteName=None):\n",
" noteName = self._noteNameCheck(noteName)\n",
" del self.notes[noteName][entry]\n",
" return self.notes\n",
" \n",
" def markEntry(self, entry, noteName=None):\n",
" noteName = self._noteNameCheck(noteName)\n",
" self.notes[noteName][entry]=\"marked\"\n",
" return self.notes\n",
" \n",
"NotepadInstance = Notepad()\n",
"NotepadInstance.addNote(\"Shopping\")\n",
"NotepadInstance.addEntry(\"coffee\")\n",
"NotepadInstance.addEntry(\"milk\")\n",
"NotepadInstance.addEntry(\"break\")\n",
"NotepadInstance.addEntry(\"chocolate\")\n",
"NotepadInstance.markEntry(\"chocolate\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 101,
......
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Solutions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Read in some of your data with pandas, plot it and get the main statistics on the data.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"%matplotlib inline\n",
"import cufflinks as cf\n",
"cf.go_offline()\n",
"\n",
"fp=r\"M:\\Projekte\\2013_UWRM\\3_messen und daten\\Messstellen\\Pegel Kreischa\\Q_Kreischa.txt\"\n",
"my_df=pd.read_csv(fp,parse_dates=True,index_col=0,sep=\",\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"my_df.iplot(secondary_y=\"q\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(my_df.describe())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write a class, that takes a filepath as an argument when it is initialized. Create a method, that takes a string as an argument and returns the number of occurances of that string in that file."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import re\n",
"\n",
"class StrCount():\n",
" def __init__(self,filepath):\n",
" self.filepath=filepath\n",
" return\n",
" \n",
" def count(self,string):\n",
" count=0\n",
" with open(self.filepath) as file:\n",
" for line in file:\n",
" count+=len(line.split(string))-1\n",
" return count"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"ename": "FileNotFoundError",
"evalue": "[Errno 2] No such file or directory: 'C:\\\\Users\\\\Gabi\\\\Documents\\\\Python\\\\NN\\\\Inputdata\\\\PCM_MEZ_good_shape.txt'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-6-cdb379e1f3ca>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mfilepath\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34mr\"C:\\Users\\Gabi\\Documents\\Python\\NN\\Inputdata\\PCM_MEZ_good_shape.txt\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mcount\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mStrCount\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfilepath\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcount\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\";\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcount\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;31m# if this takes too long it might be the server connection... (depending on the file size)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m<ipython-input-5-e09a27b1721e>\u001b[0m in \u001b[0;36mcount\u001b[0;34m(self, string)\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mcount\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mstring\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0mcount\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfilepath\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mfile\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 11\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mline\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mfile\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0mcount\u001b[0m\u001b[0;34m+=\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mline\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msplit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstring\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'C:\\\\Users\\\\Gabi\\\\Documents\\\\Python\\\\NN\\\\Inputdata\\\\PCM_MEZ_good_shape.txt'"
]
}
],
"source": [
"filepath=r\"C:\\Users\\Gabi\\Documents\\Python\\NN\\Inputdata\\PCM_MEZ_good_shape.txt\"\n",
"count=StrCount(filepath).count(\";\")\n",
"print(count)\n",
"\n",
"# if this takes too long it might be the server connection... (depending on the file size)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a function that takes an arbitrary number of inputs and prints them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#this function only takes list like entries\n",
"def arbitrary_list(*arguments):\n",
" print(arguments)\n",
" \n",
"arbitrary_list(2,3,4,5,4,3,2,4,[432],[{2:3}])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#this function only takes list like entries\n",
"def arbitrary_dict(**dictarguments):\n",
" print(dictarguments)\n",
" \n",
"arbitrary_dict(a=3,b=4,wer=88)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#this function can do all list arguments must come before dict arguments\n",
"def arbitrary(*list_args,**dict_args):\n",
" print(list_args)\n",
" print(dict_args)\n",
" \n",
"arbitrary(2,3,4,5,6,a=3,b=33,d=\"dd\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write a function, that creates the fibonacci sequence up to the n'th term."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0,\n",
" 1,\n",
" 1,\n",
" 2,\n",
" 3,\n",
" 5,\n",
" 8,\n",
" 13,\n",
" 21,\n",
" 34,\n",
" 55,\n",
" 89,\n",
" 144,\n",
" 233,\n",
" 377,\n",
" 610,\n",
" 987,\n",
" 1597,\n",
" 2584,\n",
" 4181,\n",
" 6765,\n",
" 10946,\n",
" 17711,\n",
" 28657,\n",
" 46368]"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# non-recursive\n",
"def Fibonacci2(n):\n",
" if n<=0:\n",
" raise ValueError(\"The input must be larger 0.\")\n",
" fibo=[0,1]\n",
" if n==1:\n",
" return fibo[0]\n",
" elif n==2:\n",
" return fibo\n",
" else:\n",
" for run in range(n-2):\n",
" fibo.append(fibo[-1]+fibo[-2])\n",
" return fibo\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Make python list of all files in the current directory and sort them by their file type."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"# list all contest\n",
"foldercontent=os.listdir()\n",
"\n",
"#filter files\n",
"files=[file for file in foldercontent if os.path.isfile(file)]\n",
"\n",
"#sort key makes sure i sort by the file ending\n",
"def sortkey(x):\n",
" return x.split(\".\")[1]\n",
"# sorting\n",
"files.sort(key=sortkey)\n",
"\n",
"print(files)"
]
}
],
"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.6.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Tasks"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Read in some of your data with pandas, plot it and get the main statistics on the data.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write a class, that takes a file as an argument when it is initialized. Create a method, that takes a string as an argument and returns the number of occurances of that string in that file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a function that takes an arbitrary number of inputs and prints them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write a function, that creates the fibonacci sequence up to the n'th term."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Make python list all files in the current directory."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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.6.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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.6.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
This diff is collapsed.
#################################################################################################################
## Package
class Tank:
def __init__(self, level, rate, upstream_tanks=None):
self.level = level
self.rate = rate
self.upstream_tanks = upstream_tanks
return
@property # allows the method use without brackets
def Q(self):
tank_area = 1
return self.level * self.rate / tank_area
class LevelGauge:
def __init__(self,tank):
self.tank = tank
self.data = []
return
def take_measurement(self):
self.data.append(self.tank.level)
return
class Network:
def __span_network(self, i):
self.tanks[i] = Tank(levels[i], rates[i], upstream_tanks=network_structure.get(i))
if network_structure.get(i) is not None:
for tank in network_structure.get(i):
#recursion
self.__span_network(tank)
def generate(self, network_structure, levels, rates):
self.final_tank = max(network_structure.keys())
if network_structure[self.final_tank] == []:
print("The last tank has no upstream tanks. The network structure you provided is invalid.")
else: