Archive for the ‘Programmierung’ Category.

Approximating Pi with Python

One of the many approximations of Pi is the Gregory-Leibniz series (image source Wikipedia):

Leibnis Series for Pi

Here is an implementation in Python:

# -*- coding: utf-8 -*-
"""
Created on Sat Mar 25 06:52:11 2017
@author: Uwe Ziegenhagen
"""
 
sum = 0
factor = -1
 
for i in range(1, 640000, 2):
        sum = sum + factor * 1/i
        factor *= -1
        # print(sum)
 
print(-4*sum)

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website

Russische Bauernmultiplikation mit Python

Durch eine SX Frage bin ich auf das Verfahren der „Russischen Bauernmultiplikation“ gestoßen, mit der man ohne Multiplikation ganzzahlige Zahlen miteinander multiplizieren kann. Just for Fun hier die Python-Implementierung:

# -*- coding: utf-8 -*-
"""
Created on Sat Mar 18 10:04:40 2017
 
@author: Uwe Ziegenhagen
"""
import pandas as pd
from math import floor
 
def russianPeasantMultiply(a, b):
    assert a > 1
    assert b > 0    
    data = pd.DataFrame([[a, b]], columns=list('ab'))
    while a > 1:
        a = floor(a/2)
        b = b + b
        data.loc[len(data)]=[a, b]
    data = data[data['a'] % 2 == 1]    
    return(data.b.sum())
 
print(russianPeasantMultiply(63, 17))

Ohne pandas geht es sicher auch, aber pandas macht es etwas einfacher…

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website

Generating a normal distribution table with SciPy

Here’s a simple example how one can generate a normal distribution table with Python and scipy so that it can be imported into LaTeX.

Example-03.zip

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 13 21:14:17 2017
@author: Uwe Ziegenhagen, ziegenhagen@gmail.com
 
Creates a CDF table for the standard normal distribution
 
use booktabs package in the preamble and put 
the generated numbers inside (use only one backslash!)
 
\\begin{tabular}{r|cccccccccc} \\toprule
<output here>
\\end{tabular}
"""
 
from scipy.stats import norm
 
print(norm.pdf(0))
print(norm.cdf(0),'\r\n')
 
horizontal = range(0,10,1)
vertikal = range(0,37)
 
header = ''
for i in horizontal:
    header = header + '& ' + str(i/100)
 
print(header, '\\\\ \\midrule')
 
for j in vertikal:  
    x = j/10
    print('\\\\', x)
    for i in horizontal:
        y = x + i/100
        print('& ', "{:10.4f}".format(norm.cdf(y),4))
 
 
print('\\\\ \\bottomrule \r\n')

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website

Win32 Dialoge mit Python auswerten

http://stackoverflow.com/questions/4485610/python-message-box-without-huge-library-dependancy zeigt, wie man Windows Standard-Dialoge (wie MessageBox und JaNeinAbbrechen) mit Python auswerten kann:

# using ctypes
import ctypes
MessageBox = ctypes.windll.user32.MessageBoxW
MessageBox(None, 'Hello World', 'This is the window title', 0)
 
# using win32ui
import win32ui
win32ui.MessageBox('This is the message', 'Window Title')
 
# using win32con
import win32con
 
result = win32ui.MessageBox('The Message', 'The Title', win32con.MB_YESNOCANCEL)
 
if result == win32con.IDYES:
    win32ui.MessageBox('You pressed "Yes"')
elif result == win32con.IDNO:
    win32ui.MessageBox('You pressed "No"')
elif result == win32con.IDCANCEL:    
    win32ui.MessageBox('You pressed "Cancel"')

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website

Daten arrangieren mit pandas melt

Hier ein kurzes Beispiel, wie man mittels melt bestimmte Daten in die richtige Form bekommt.

Ausgangspunkt ist der folgende Datensatz:

Zum Auswerten ist der nicht optimal, ich möchte die Monatswerte gern untereinander haben. Mittels melt geht das ganz einfach:

# -*- coding: utf-8 -*-
 
import pandas as pd
 
data = pd.read_excel('meltdata.xlsx')
 
print(data.shape[1], 'columns and', data.shape[0], 'rows')
 
print(list(data))
 
melted = pd.melt(data, id_vars=['Name', 'ColumnB', 'ColumnC'], 
                 value_vars=['Januar', 'Februar', 'März', 'April', 'Mai', 
                 'Juni', 'Juli', 'August', 'September', 'Oktober', 
                 'November', 'Dezember'])
 
print(melted)
      Name    ColumnB ColumnC   variable  value
0 Donald 1978-09-03 Hello Januar 98
1 Micky 1945-05-04 World Januar 29
2 Minnie 1946-07-05 Foo Januar 57
3 Pluto 1998-07-08 Bar Januar 28
4 Donald 1978-09-03 Hello Februar 31
5 Micky 1945-05-04 World Februar 41
6 Minnie 1946-07-05 Foo Februar 24
...

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website

Auto-Documenting Python Code

A while ago I thought about auto-documenting Python code, here’s what resulted from those experiments. (It’s far away from production quality, so use at your own risk)#

Let’s assume we have a Python file without docstrings:

class HalloWelt:
 
	def Hallo(welt):
		return welt
 
 
print(HalloWelt.Hallo("Welt"))

My experimental Python code:

import re
 
class Dokumenter:
	"""
	Fügt einer bestehenden Python-Datei Docstrings hinzu, falls keine vorhanden sind.
	"""
 
	def dokumentme(filename):
		print(">> Prüfe",filename,"auf Docstrings\n")
 
		with open(filename+"_bak", 'w') as outfile:
			with open(filename, 'r') as infile:
				rowIter= iter(infile)
				for row in rowIter:
					# schreibe die Zeile auf jeden Fall in die Zieldatei
					outfile.write(row)
					# Ist in der Zeile ein 'def ' vorhanden?
					if "def " in row:
						# suche erstes Zeichen, das kein Docstring ist
						index = re.search('\S', row).start()
						whitespace = row[:index]
						whitespaceLen = len(whitespace)
						if " " in whitespace:
							blanks = True
						else:
							blanks = False					
						print(whitespaceLen,blanks)	
 
 
						print(">> Funktionsdefinition gefunden")
						print(">> Schreibe Docstring")
						print(">> Whitespaces",index)
						outfile.write('"""\nHallo Welt\n"""\n')
					print(row)
 
Dokumenter.dokumentme("dokme.py")
# Tests, Datei mit und ohne Dokstring,unterschiedliche Einrückungstiefe
# extrahiere die Parameter

Output:

class HalloWelt:
 
	def Hallo(welt):
"""
Hallo Welt
"""
		return welt
 
 
print(HalloWelt.Hallo("Welt"))

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website

Mit Python rekursiv Verzeichnisse auswerten

Hier ein kurzer Code-Schnipsel (basierend auf https://www.tutorialspoint.com/python/os_walk.htm), der Verzeichnisse rekursiv durchläuft und jeweils den kompletten Pfad in einem pandas DataFrame speichert. Dateien werden ignoriert, dies kann durch die Überarbeitung des „pass“ Teils angepasst werden.

import os
import sys
import pandas as pd
 
paths = pd.DataFrame(columns={'Path'})
 
rootdir = 'somepath’
 
for root, directories, filenames in os.walk(rootdir):
    for directory in directories:
        paths = paths.append({'Path':(os.path.join(root, directory)).replace('\\','/')},ignore_index=True)
    for filename in filenames:
        pass
 
paths.to_clipboard()

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website

Time in Python

A short summary on Python’s timestamps:

import datetime
 
now = datetime.datetime.now()
 
print(now.strftime('%Y-%m-%d %H:%M'))
print(now.isoformat())

From the module’s documentation:

Directive Meaning
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time
representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number
[00,23].
%I Hour (12-hour clock) as a decimal number
[01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first
day of the week) as a decimal number [00,53].
All days in a new year preceding the first
Sunday are considered to be in week 0.
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first
day of the week) as a decimal number [00,53].
All days in a new year preceding the first
Monday are considered to be in week 0.
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number
[00,99].
%Y Year with century as a decimal number.
%z Time zone offset indicating a positive or
negative time difference from UTC/GMT of the
form +HHMM or -HHMM, where H represents decimal
hour digits and M represents decimal minute
digits [-23:59, +23:59].
%Z Time zone name (no characters if no time zone
exists).
%% A literal '%' character.

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website

Slides from my 2016 Froscon Presentation „Using Python for Scientific Research“

Here are my slides from the Froscon 2016 presentation „Using Python for Scientific Research“.

Slides: Froscon_Slides_2016

Video: Video Recording (The screen was flickering most of the time, pretty annoying and distracting)

I will continously update and expand this presentation during the next months, if you want to receive updates follow the GitHub repository: https://github.com/UweZiegenhagen/2016-Python-Data-Analysis-Slides/

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website

Parsing Emacs Orgmode files with Python

Here’s some experimental (alpha) code to parse Emacs Orgmode files. It’s far from complete, I only aim at parsing basic TODO strings with level (**), status (TODO, DONE), priority (#A, #B, #C), task and tags.

2016-09-03: It takes my actual orgmode file, so it’s working fine.

2016-09-04: I created a github repo, code updates will be added there, only: https://github.com/UweZiegenhagen/python-orgmode-parser

# -*- coding: utf-8 -*-
import re
 
def parseEmaceOrgmode(s):
    r = '^([\*]+)?\s?(TODO|PROGRESSING|FEEDBACK|VERIFY|POSTPONED|DELEGATED|CANCELLED|DONE)?\s?(\[#[A|B|C]\])?\s?(.*?)\s*(:(.*):)?$'    
    m = re.search(r,s)
    level = m.group(1)
    if (level is not None):
        level = len(level)
    prio = m.group(3)
    if (prio is not None):
        prio = prio[2:3]
    tags = []
    a = m.group(5)
    if a != None:
        b = len(a)-1
        a= a[1:b]
        a = a.split(':')
    tags.append(a)
    return(level, m.group(2), prio, m.group(4), tags)
 
with open("../orgmode.org", "r") as ins:
    for line in ins:
        level, status, priority, task, tags = parseEmaceOrgmode(line)
        if level is not None:        
            print('Level:', level)
            print('Status:', status)
            print('Priority:', priority)
            print('Task:', task)
            print('Tags:',tags,'\n\n')

Uwe

Uwe Ziegenhagen has been working with LaTeX for more than a decade. Besides TeX/LaTeX he likes to work with Python, Rasberry/Arduino and his digital camera.

More Posts - Website