| Hosted by CoCalc | Download
Kernel: Python 2 (system-wide)
#Ordne einer Variabeln eine Zahl zu a=29 #Gib die Variable aus print('Nur die Variable',a) #Addiere zu der Variablen etwas dazu print('Addition',a+20) #Auch eine Addition .. a+=20 print('Addition',a) #Multipliziere die Zahl mit 2 print('Multiplikation',2*a) #Auch eine Multiplikation a*=2 print('Multiplikation',a) #Dividiere print('Division',a/3.) #Dividiere nochmal mit integer divison. Was ist der Unterschied? print('IntegerFloorDivision',a//3) #Wandle ein paar Zahlen in Buchstaben um mit der Funktion chr() print('20 als Buchstabe',chr(20)) print('66 als Buchstabe',chr(66)) #Erzeuge eine Liste von Zahlen mit range(1,255,1) wobei das der Reihe nach heisst: #Starte bei 1, gehe bis 255, und tue es in 1er Schritten #wie oben wird auf jede Zahl die Umwandlung in Buchstaben mit chr() ausgeführt #Das ganze wird als Liste der Variable a zugeordnet a=[chr(i) for i in range(1,255,5)] print('1 bis und mit 255 jeder 5 Buchstabe:',a) #Spreche ein paar der Elemente in der Liste an: Einzeln oder als von # bis und mit ohne letzte Zahl, e.g. 127 bis und mit 130, aber nicht mit 131 print('Index 0 der Buchstabenliste',a[0]) print('Verschiedene Indices der Buchstabenliste',a[127/5], a[128/5], a[129/5], a[127/5:131/5]) #gehe durch alle Buchstabenmöglichkeiten durch die in einem Byte = 8 Bit #= 2^8 = 2**8 vorkommen können, aber in 5er Schritten for i in range(1,255,5): print(i,'is the letter',unichr(i))
('Nur die Variable', 29) ('Addition', 49) ('Addition', 49) ('Multiplikation', 98) ('Multiplikation', 98) ('Division', 32.666666666666664) ('IntegerFloorDivision', 32) ('20 als Buchstabe', '\x14') ('66 als Buchstabe', 'B') ('1 bis und mit 255 jeder 5 Buchstabe:', ['\x01', '\x06', '\x0b', '\x10', '\x15', '\x1a', '\x1f', '$', ')', '.', '3', '8', '=', 'B', 'G', 'L', 'Q', 'V', '[', '`', 'e', 'j', 'o', 't', 'y', '~', '\x83', '\x88', '\x8d', '\x92', '\x97', '\x9c', '\xa1', '\xa6', '\xab', '\xb0', '\xb5', '\xba', '\xbf', '\xc4', '\xc9', '\xce', '\xd3', '\xd8', '\xdd', '\xe2', '\xe7', '\xec', '\xf1', '\xf6', '\xfb']) ('Index 0 der Buchstabenliste', '\x01') ('Verschiedene Indices der Buchstabenliste', '~', '~', '~', ['~']) (1, 'is the letter', u'\x01') (6, 'is the letter', u'\x06') (11, 'is the letter', u'\x0b') (16, 'is the letter', u'\x10') (21, 'is the letter', u'\x15') (26, 'is the letter', u'\x1a') (31, 'is the letter', u'\x1f') (36, 'is the letter', u'$') (41, 'is the letter', u')') (46, 'is the letter', u'.') (51, 'is the letter', u'3') (56, 'is the letter', u'8') (61, 'is the letter', u'=') (66, 'is the letter', u'B') (71, 'is the letter', u'G') (76, 'is the letter', u'L') (81, 'is the letter', u'Q') (86, 'is the letter', u'V') (91, 'is the letter', u'[') (96, 'is the letter', u'`') (101, 'is the letter', u'e') (106, 'is the letter', u'j') (111, 'is the letter', u'o') (116, 'is the letter', u't') (121, 'is the letter', u'y') (126, 'is the letter', u'~') (131, 'is the letter', u'\x83') (136, 'is the letter', u'\x88') (141, 'is the letter', u'\x8d') (146, 'is the letter', u'\x92') (151, 'is the letter', u'\x97') (156, 'is the letter', u'\x9c') (161, 'is the letter', u'\xa1') (166, 'is the letter', u'\xa6') (171, 'is the letter', u'\xab') (176, 'is the letter', u'\xb0') (181, 'is the letter', u'\xb5') (186, 'is the letter', u'\xba') (191, 'is the letter', u'\xbf') (196, 'is the letter', u'\xc4') (201, 'is the letter', u'\xc9') (206, 'is the letter', u'\xce') (211, 'is the letter', u'\xd3') (216, 'is the letter', u'\xd8') (221, 'is the letter', u'\xdd') (226, 'is the letter', u'\xe2') (231, 'is the letter', u'\xe7') (236, 'is the letter', u'\xec') (241, 'is the letter', u'\xf1') (246, 'is the letter', u'\xf6') (251, 'is the letter', u'\xfb')
#### Erzeuge eine Liste a=list() b=[] print('Zeige die Liste',a,b) #Fülle die Liste auf a.append(2) a.extend([3,2]) print('Zeige die Liste',a) #Listen werden mit Indices angesprochen print('Mit Indices',a[0],a[1]) #Auch negative Indices gehen print('Mit negativen Indices',a[-1],a[-2]) #An einer beliebigen Stelle etwas einfügen a.insert(0,'Hier ist der Anfang') #Kann auch am Ende etwas eingefügt werden? a.insert(-1,'Ist hier das Ende?') print(a) #Ja und nein, es ist das Ende minus 1, sonst wie oben extend/append verwenden #Liste durchsuchen print('Die Zahl 2 findet sich an der Stelle',a.index(2),'Zahl an dem Index, nur zur Sicherheit',a[a.index(2)]) #Eine bisschen grössere Liste alist=[i % 5 for i in range(20)] #Sortiere die Liste alist.sort() print('Liste sortiert',alist) #Erweitere die Liste mit Zahlen von 0 bis 9 alist.extend(range(10)) print('Liste erweitet',alist) #Entferne Elemente aus der Liste alist.remove(5) print('Zahl 5 einmal entfernt',alist) alist.pop() print('Letztes Element entfernt',alist) #Länge der Liste alistlen=len(alist) [alist.pop(i) for i in range(2,alistlen/3-1,3)] print('Jedes dritte Element ab Index 5 entfernt',alist) #Drehe die Liste um alist=alist[::-1] print('Gedrehte Liste',alist) #Nur die ersten Elemente: 0 1 2, obwohl der Index 3 da steht ist er nicht enthalten print('Erste paar Elemente',alist[0:3]) #Nur jedes dritte Element print('Jedes dritte Element',alist[0::3]) #Nur jedes zweite Element, aber vom Ende her print('Jedes zweite Element von Ende her',alist[::-2])
('Zeige die Liste', [], []) ('Zeige die Liste', [2, 3, 2]) ('Mit Indices', 2, 3) ('Mit negativen Indices', 2, 3) ['Hier ist der Anfang', 2, 3, 'Ist hier das Ende?', 2] ('Die Zahl 2 findet sich an der Stelle', 1, 'Zahl an dem Index, nur zur Sicherheit', 2) ('Liste sortiert', [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]) ('Liste erweitet', [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) ('Zahl 5 einmal entfernt', [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 0, 1, 2, 3, 4, 6, 7, 8, 9]) ('Letztes Element entfernt', [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 0, 1, 2, 3, 4, 6, 7, 8]) ('Jedes dritte Element ab Index 5 entfernt', [0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 0, 1, 2, 3, 4, 6, 7, 8]) ('Gedrehte Liste', [8, 7, 6, 4, 3, 2, 1, 0, 4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 0, 0, 0]) ('Erste paar Elemente', [8, 7, 6]) ('Jedes dritte Element', [8, 4, 1, 4, 3, 3, 2, 1, 0]) ('Jedes zweite Element von Ende her', [0, 0, 1, 2, 2, 3, 3, 4, 4, 0, 2, 4, 7])
Units=['B','KB','MB','GB','TB','PB'] for i in range(33): _=2**i div=0 while _ >= 1024: div+=1 _/=1024 print _, Units[div], 'from',2**i,'Bytes'
1 B from 1 Bytes 2 B from 2 Bytes 4 B from 4 Bytes 8 B from 8 Bytes 16 B from 16 Bytes 32 B from 32 Bytes 64 B from 64 Bytes 128 B from 128 Bytes 256 B from 256 Bytes 512 B from 512 Bytes 1 KB from 1024 Bytes 2 KB from 2048 Bytes 4 KB from 4096 Bytes 8 KB from 8192 Bytes 16 KB from 16384 Bytes 32 KB from 32768 Bytes 64 KB from 65536 Bytes 128 KB from 131072 Bytes 256 KB from 262144 Bytes 512 KB from 524288 Bytes 1 MB from 1048576 Bytes 2 MB from 2097152 Bytes 4 MB from 4194304 Bytes 8 MB from 8388608 Bytes 16 MB from 16777216 Bytes 32 MB from 33554432 Bytes 64 MB from 67108864 Bytes 128 MB from 134217728 Bytes 256 MB from 268435456 Bytes 512 MB from 536870912 Bytes 1 GB from 1073741824 Bytes 2 GB from 2147483648 Bytes 4 GB from 4294967296 Bytes 1
unit='1 TB' units=['B','KB','MB','GB','TB'] # Units=Units[::-1] tb=(10.**3)**4 # print(unit,'is',tb,'Bytes') for steps in range(len(units)): print('That is', tb/(1024**(steps)),units[steps])
('That is', 1000000000000.0, 'B') ('That is', 976562500.0, 'KB') ('That is', 953674.31640625, 'MB') ('That is', 931.3225746154785, 'GB') ('That is', 0.9094947017729282, 'TB')
import os os.curdir os.path.abspath(os.curdir) files= os.listdir(os.path.abspath('.')) print(files) print(dir(files[0])) # Verändere hier die Nummer um alles zu lesen was in dem Verzeichnis ist for _ in files[:3]: try: with open(os.path.abspath('.')+os.path.sep+_) as FileObj: linecnt=0 print('*********************') print(FileObj.name) print('*********************') for line in FileObj: linecnt+=1 print('Line',linecnt,line) if linecnt >= 10: break except IOError as err: print(err)
['.smc', '.2016-09-23-100330.html.sage-chat', '.sage', 'RasterVektor.html', 'aaaaa', '.jupyter', '.2016-10-13-165046.ipynb.sage-jupyter', 'another', '2016-09-23-100330.ipynb', '.2016-10-13-163950.py.sage-chat', '.bashrc', '.RasterVektor.ipynb.sage-jupyter', '.snapshots', '.bash_profile', '.2016-09-23-100330.ipynb.sage-jupyter2', '2016-09-23-100330.html', '.2016-09-23-100330.ipynb.sage-jupyter', '.ipynb_checkpoints', '.local', '.ssh', 'RasterVektor.ipynb', 'HelloWorld'] ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] [Errno 21] Is a directory: '/home/user/.smc' ********************* /home/user/.2016-09-23-100330.html.sage-chat ********************* [Errno 21] Is a directory: '/home/user/.sage'
import subprocess import os files=os.listdir('.') print(files) commands=['w','who','whoami','users','ps aux','df -hl','free -hl','ls -lh','tail '+files[1]] for cmd in commands: print('**********************************************') print('Executing',cmd) print('Output is') print(subprocess.check_output(cmd.split()))
['.jupyter', '2016-09-23-100330.ipynb', 'another', '.local', '.sage', 'HelloWorld', '.bash_profile', '.bashrc', '2016-09-23-100330.html', '.smc', '.forever', '.ipynb_checkpoints', '.2016-09-23-100330.ipynb.sage-jupyter', '.2016-09-23-100330.html.sage-chat', 'aaaaa'] ********************************************** ('Executing', 'w') Output is 13:24:48 up 1:14, 1 user, load average: 1.91, 1.50, 1.37 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT ********************************************** ('Executing', 'who') Output is salvus pts/0 2016-10-12 12:10 (10.240.0.27) ********************************************** ('Executing', 'whoami') Output is 508423d78ea74c0f917e73085e443415 ********************************************** ('Executing', 'users') Output is salvus ********************************************** ('Executing', 'ps aux') Output is USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 1028827+ 5940 0.0 0.1 908884 35092 ? Ssl 12:11 0:00 /usr/bin/nodejs /usr/lib/node_modules/forever/bin/monitor /usr/lib/node_modules/smc-project/local_hub.coffee 1028827+ 5951 0.3 0.3 1264296 88684 ? Sl 12:11 0:13 node /usr/bin/coffee /usr/lib/node_modules/smc-project/local_hub.coffee 1028827+ 8695 0.1 0.1 346600 46244 ? Sl 12:12 0:05 python /projects/sage/sage-7.3/local/bin/ipython notebook --port-retries=0 --no-browser --NotebookApp.mathjax_url=/static/mathjax/MathJax.js --NotebookApp.base_url=/508423d7-8ea7-4c0f-917e-73085e443415/port/jupyter/ --NotebookApp.base_kernel_url=/508423d7-8ea7-4c0f-917e-73085e443415/port/jupyter/ --ip=10.240.0.31 --port=22985 1028827+ 22675 0.0 0.0 17200 2500 ? R 13:24 0:00 ps aux 1028827+ 25561 0.1 0.2 1026780 68208 ? Ssl 12:20 0:04 python -E -m ipykernel --matplotlib=inline -f /projects/508423d7-8ea7-4c0f-917e-73085e443415/.local/share/jupyter/runtime/kernel-674a8ddb-b37d-422b-945a-179f592abba1.json ********************************************** ('Executing', 'df -hl') Output is Filesystem Size Used Avail Use% Mounted on udev 13G 0 13G 0% /dev tmpfs 2.6G 25M 2.6G 1% /run /dev/sda1 40G 27G 11G 72% / tmpfs 13G 0 13G 0% /dev/shm tmpfs 5.0M 0 5.0M 0% /run/lock tmpfs 13G 0 13G 0% /sys/fs/cgroup /dev/sdb1 50G 73M 47G 1% /tmp /dev/sdb2 443G 319G 102G 76% /projects /dev/sdd 30G 15G 13G 54% /projects/data/RNASEQ tmpfs 2.6G 0 2.6G 0% /run/user/0 tmpfs 2.6G 0 2.6G 0% /run/user/1001 tmpfs 2.6G 0 2.6G 0% /run/user/1010 ********************************************** ('Executing', 'free -hl') Output is total used free shared buffers cached Mem: 25G 23G 1.6G 23M 18M 275M Low: 25G 23G 1.6G High: 0B 0B 0B -/+ buffers/cache: 23G 1.9G Swap: 63G 1.1G 62G ********************************************** ('Executing', 'ls -lh') Output is total 2.8M -rw-r----- 1 508423d78ea74c0f917e73085e443415 508423d78ea74c0f917e73085e443415 1.5M Oct 12 13:20 2016-09-23-100330.html -rw-r----- 1 508423d78ea74c0f917e73085e443415 508423d78ea74c0f917e73085e443415 1.3M Oct 12 13:20 2016-09-23-100330.ipynb drwxr-x--- 2 508423d78ea74c0f917e73085e443415 508423d78ea74c0f917e73085e443415 4.0K Oct 6 14:23 aaaaa drwxr-x--- 2 508423d78ea74c0f917e73085e443415 508423d78ea74c0f917e73085e443415 4.0K Oct 6 14:23 another drwxr-x--- 2 508423d78ea74c0f917e73085e443415 508423d78ea74c0f917e73085e443415 4.0K Oct 6 14:23 HelloWorld ********************************************** ('Executing', 'tail 2016-09-23-100330.ipynb') Output is "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }
#Fakulät Iterativ def f(n): f1,f2=1,2 while f2<=n: f1,f2=f1*f2,f2+1 return(f1) for i in range(1,10): print('Fakultaet von '+str(i)+':',f(i))
('Fakultaet von 1:', 1) ('Fakultaet von 2:', 2) ('Fakultaet von 3:', 6) ('Fakultaet von 4:', 24) ('Fakultaet von 5:', 120) ('Fakultaet von 6:', 720) ('Fakultaet von 7:', 5040) ('Fakultaet von 8:', 40320) ('Fakultaet von 9:', 362880)
#Rekursion def rekur(n): print(str(n) + ' going down') a=n if n > 1: n=rekur(n/2) print(str(a*2)+' going back up') return(n) #nun die Aufrufe der Funktion rekur(11) rekur(10) rekur(7)
11 going down 5 going down 2 going down 1 going down 2 going back up 4 going back up 10 going back up 22 going back up 10 going down 5 going down 2 going down 1 going down 2 going back up 4 going back up 10 going back up 20 going back up 7 going down 3 going down 1 going down 2 going back up 6 going back up 14 going back up
1
#Fakultät Rekursiv def f(n): if n<=1: return(1) else: return(f(n-1)*n) for i in range(1,10): print('Fakultaet von '+str(i)+':',f(i))
('Fakultaet von 1:', 1) ('Fakultaet von 2:', 2) ('Fakultaet von 3:', 6) ('Fakultaet von 4:', 24) ('Fakultaet von 5:', 120) ('Fakultaet von 6:', 720) ('Fakultaet von 7:', 5040) ('Fakultaet von 8:', 40320) ('Fakultaet von 9:', 362880)
#Addition von zwei Binärzahlen def binary_addition(num1,num2): if num1.__len__() <= 8: num1 = '0' * (8 - num1.__len__()) + num1 if num2.__len__() <= 8: num2 = '0' * (8 - num2.__len__()) + num2 print(' '.join(['Adding', num1, 'and', num2])) num1,num2,newnum, oldcarry,i = [int(i) for i in num1],[int(i) for i in num2],' ', 0,num1.__len__() - 1 print(1, 2, chr(79), chr(67)) while i >= 0: newcarry = int((num2[i] and num1[i]) or (oldcarry and (num1[i] != num2[i]))) newnum = str(int((num1[i] != num2[i]) != oldcarry)) + newnum print(num1[i], num2[i], oldcarry, newcarry) oldcarry,i = newcarry,i-1 return(newnum) #Hier kannst du auch die Nummern ändern,.. print(binary_addition('001111','1100000'))
Adding 00001111 and 01100000 (1, 2, 'O', 'C') (1, 0, 0, 0) (1, 0, 0, 0) (1, 0, 0, 0) (1, 0, 0, 0) (0, 0, 0, 0) (0, 1, 0, 0) (0, 1, 0, 0) (0, 0, 0, 0) 01101111
def binary_substraction(num1,num2): if num1.__len__() <= 8: num1 = '0' * (8 - num1.__len__()) + num1 if num2.__len__() <= 8: num2 = '0' * (8 - num2.__len__()) + num2 print('Subtracting', num2, 'from', num1) num1,num2,newnum, oldcarry,i = [int(i) for i in num1],[int(i) for i in num2],' ', 0,num1.__len__() - 1 print(1, 2, chr(79), chr(66)) while i >= 0: newcarry = int((num2[i] and not num1[i]) or (oldcarry and not (num1[i] != num2[i]))) newnum = str(int((num1[i] != num2[i]) != oldcarry)) + newnum print(num1[i], num2[i], oldcarry, newcarry) oldcarry,i = newcarry,i-1 return(newnum) print(binary_substraction('001111','1100000'))
('Subtracting', '01100000', 'from', '00001111') (1, 2, 'O', 'B') (1, 0, 0, 0) (1, 0, 0, 0) (1, 0, 0, 0) (1, 0, 0, 0) (0, 0, 0, 0) (0, 1, 0, 1) (0, 1, 1, 1) (0, 0, 1, 1) 10101111
#partialsumme eines arrays def arr_mean(arr,i): psum=0 if i>=arr.__len__(): i=arr.__len__() for a in range(i): psum+=arr[a] print(arr[a]) print(psum,' partial sum at index',i) return(psum / float(i)) arr=range(20) arr[:]=[x**3-x*3 for x in arr] print('Numbers in array\n',arr) print(arr_mean(arr,23))
('Numbers in array\n', [0, -2, 2, 18, 52, 110, 198, 322, 488, 702, 970, 1298, 1692, 2158, 2702, 3330, 4048, 4862, 5778, 6802]) 0 -2 2 18 52 110 198 322 488 702 970 1298 1692 2158 2702 3330 4048 4862 5778 6802 (35530, ' partial sum at index', 20) 1776.5
def magic_number(num): diff, cnt = 0, 0 initnum = num num = int(num) # so nobody can wrongly use a floating value if num <=1000: num+=1000 num = str(divmod(num, 10000)[1]) # because its a tuple while diff != 6174: num = [i for i in num] num.sort(reverse=1) # should work with True, notice the uppercase dnum = ''.join(num) num.sort() anum = ''.join(num) diff = int(dnum) - int(anum) print('Calculating: ', dnum, ' - ', anum, ' = ', diff) num, cnt = str(diff), cnt + 1 print('New Number is', num) if diff <= 0: print('Sorry, it doesn\'t work for',initnum) return (-1) return (diff // 147) print(magic_number(3233))
('Calculating: ', '3332', ' - ', '2333', ' = ', 999) ('New Number is', '999') ('Calculating: ', '999', ' - ', '999', ' = ', 0) ('New Number is', '0') ("Sorry, it doesn't work for", 3233) -1
def magicnumber(j,quiet=False): j %= 10000 if j < 1000: print('Number too small, adding 1000') j += 1000 # so nobody can wrongly use a floating num = int(j) # Initialisation for loop bnum = num cnt ,diff = 0,-1 num = str(divmod(num, 100000)[1]) # because its a tuple while diff != 6174 and diff != 0: #make a list out of the number num = [i for i in num] anum = ''.join(sorted(num)) dnum = ''.join(reversed(anum)) diff = int(dnum) - int(anum) if not quiet: print(' '.join([str(_) for _ in ['Calculating: ', dnum, '-', anum, '=', str(diff)]])) num = str(diff) cnt += 1 if not quiet: print('New Number is '+str(num)) if diff == 0: print('Sorry doesn\'t work for '+str(bnum)) else: print('Endresult for',bnum,'after ', cnt, 'iterations\n', diff, '/ 147 = ', diff // 147) magicnumber(3233) # Try all numbers? #for i in range(1000,9999,1): # magicnumber(i,quiet=True)
Calculating: 3332 - 2333 = 999 New Number is 999 Calculating: 999 - 999 = 0 New Number is 0 Sorry doesn't work for 3233
import matplotlib.pyplot as plt import seaborn as sns import numpy as np x=range(32) plt.semilogy(x,[2**_ for _ in x],'o-b',markerfacecolor='black',color='red',alpha=0.95,linestyle='--',markersize=5,label='2 to power of i') plt.semilogy(x,[_**2 for _ in x],'o-b',markerfacecolor='red',color='red',alpha=0.95,linestyle='--',markersize=5,label='i to power of 2') plt.xlabel('i') plt.ylabel('Anzahl') plt.title('Some Graph!') plt.legend() plt.show()
Image in a Jupyter notebook
#Bringt Plotting nach Python, i.e. Bilder, Daten usw. import matplotlib.pyplot as plt #Bringt arrays nach Python import numpy as np xsize=256 steps=512 #xsize / steps ergibt Schrittlänge, e.g. 256 / 512 = 0.5 #erzeugt ein Raster/Array mit den Ausmessungen oben x, y = np.meshgrid(np.linspace(1,xsize,num=steps), np.linspace(1,xsize,num=steps)) #erstellt die Bildgrösse in Inches (= 2.54 cm) fsize=[2.,2.] [i/2.54 for i in fsize] import matplotlib #Ein paar Parameter die wir verwenden wollen #Das Bild soll zweireihig sein, mit 3 Bildern nx,ny=3,2 #Was soll dargestellt werden? Hier erzeugen wir wieder ein Dictionary mit Beschreibung #der Rechnung und dem Inhalt. Vorsicht, die Division ist eine Floor, i.e. Integer Division #E.g. 10/3 = 3.33..., 10//3 = Abrunden(3.33) = 3 content={'X':x,'Y':y,'Addition':x+y,'Substraction':x-y,'Multiplication':x*y,'Division':x/y} #Erzeuge die Keys als Liste _c=list(content.keys()) #Welches Bild wohin soll, erste Reihe ist 1-3, zweite Reihe ist 4-6 #Also Links oben Anfang nach rechts durchgehen #Wichtig sind hier die gleichen Wörter wie in content reihenfolge={'X':1,'Y':4,'Addition':2,'Substraction':5,'Multiplication':3,'Division':6} #Was über den Bildern stehen soll.. titles=['X','Y','Addition','Substraction','Multiplication','Division'] #Setzt ein Figure Objekt auf, mit 180 DPI, dots per Inches = wie fein das Ganze ist fig=plt.figure(1,dpi=180) # Welche Colormap genommen wird, i.e. welche Nummer zu welcher Farbe wird cmap='coolwarm' #Schleife durch die Titel for i in titles: #Welche Nummer nun genommen werden soll plt.subplot(ny,nx,reihenfolge[i]) #Einige Optionen: Beide Axen darstellen, aber keine Beschriftungen # plt.tick_params(axis='both',which='both',bottom='on',top='on',right='on',left='on') #Den Titel setzen plt.title(i) #Spezialbedingung für Division, damit man die Abstufungen besser sieht. #Matplotlib macht intern eine bilineare Interpolation für Bilder, wenn nicht interpolation='none' if i != 'Division': #Fall mit NICHT Division #Zeige das Bild an (ist in dem Content Dictionary von bevor) plt.imshow(content[i], interpolation='none',cmap=cmap) else: #Fall mit Division #Zeige das Bild an (ist in dem Content Dictionary von bevor, ) plt.imshow(content[i], vmax=1,interpolation='none',cmap=cmap) #Zeige noch eine Colorbar an, das zeigt uns die effektiven Werte die im Bild sind an cbar=plt.colorbar(orientation='horizontal', pad=0.02,shrink=0.75) cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), rotation='vertical') #Setzte die Ticks an der Achse auf eine leere Liste = Unterdrücken plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) #Bevor das Bild angezeigt wird, mache den Abstand der Bilder untereinander noch kleiner! fig.tight_layout() #Zeige das Bild an plt.show()
Image in a Jupyter notebook
import scipy.ndimage.filters as filters #Bringt Plotting nach Python, i.e. Bilder, Daten usw. import matplotlib.pyplot as plt #Macht die Default Einstellungen von Matplotlib etwas schönes import seaborn as sns #Bringt arrays nach Python import numpy as np xsize,steps=256,512 x=np.random.rand(xsize,xsize) #erstellt die Bildgrösse in Inches (= 2.54 cm) fsize=[2.,2.] [i/2.54 for i in fsize] #_c=list(content.keys()) cmap='Spectral' k = np.array([[0,1,0],[1,0,1],[0,0,0]]) plt.imshow(filters.convolve(x,k), interpolation='none',cmap=cmap) cbar=plt.colorbar(orientation='horizontal',pad=0.02,shrink=0.7) cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), rotation='vertical') plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) plt.show()
Image in a Jupyter notebook
# Define helper function: # Euclidian Distance, Heron Area def euclid(a, b): return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5 def heron(sides): s = 0.5 * sum(sides) d = [s - i for i in sides] return (s * d[0] * d[1] * d[2]) ** 0.5 # Define 3 Points, any random points will do… x, y, z = [1, 1], [5, 1], [4, 5] # calculate the three sides, the order doesn't matter sides = [euclid(x, y), euclid(x, z), euclid(y, z)] # calculate area by herons formula area = heron(sides) # calculate distance of triangle height # on a calculator you would do this three times, here's a loop heights = [area*2 / i for i in sides] # print the calculated area and the three heights print(area) print(heights)
8.0 [4.000000000000002, 3.2000000000000015, 3.8805700005813293]