Machine Learning Primer -- Python Tutorial




Claudius Gros, WS 2024/25

Institut für theoretische Physik
Goethe-University Frankfurt a.M.

Expressions, Functions & Time

regular expressions

findall()   returning list with all matches
search()   returns matching object, if existing
split()   returns list of fragments
replace()   replacing one or many matches

[]  set of characters
\  special sequence (escape character)
.  as single character (except newline)
^  starts with
$  ends with
*  zero or more occurrences
+  one or more occurrences
?  zero or one occurrences
{}  exactly the specified number of occurrences
|  either or
()  capture and grouping
Copy Copy to clipboad
Downlaod Download
#!/usr/bin/env python3

import re   # regular expressions

txt = "The rain in Spain falls mostly in ..."

xFind = re.findall("in", txt)
print("xFind   : ", xFind) 

xSplit = re.split(" ", txt)
print("xSplit  : ", xSplit) 

# splitting at first position  \s  ==  space
xSplit_1 = re.split("\s", txt, 1)
print("xSplit_1: ", xSplit_1) 

# replace 3 times
xSub = re.sub("\s", "_", txt, 3)
print("xSub    : ", xSub) 

# search for an upper case "S" character in the beginning of a word 
# and print its position:
# span() returns tuple with starting/ending index 
xSpan = re.search(r"\bS\w+", txt)
print("xSpan   : ", xSpan.span())

lambda expressions

ternary expressions

Copy Copy to clipboad
Downlaod Download
#!/usr/bin/env python3

print("*************************")
print("simple lambda expressions")
print("*************************")
x = lambda a : a + 10
print("lambda    a : a + 10     :",x(5)) 

y = lambda a, b : a * b
print("lambda a, b : a * b      :",y(5, 6)) 

# line continuation
# no empty space after  '\'
z = lambda x: \
    'odd' if x%2 else 'even'   # inline 'if then else" 
#   x % 2 and 'odd' or 'even'   # identical

print("\'odd\' if x%2 else \'even\' :",z(5)) 

print()
print("**************************************")
print("function returning a lambda expression")
print("**************************************")

def myfunc(n):
  return lambda a : a * n

mytripler = myfunc(3)
# equivalent to
# mytripler = lambda a : a*3

print("return lambda a : a * n  :",mytripler(11))
   
print()
print("**************")
print("direct calling")
print("**************")
print("(lambda x: x + 1)(2)     :",(lambda x: x + 1)(2))

magic functions

Copy Copy to clipboad
Downlaod Download
#!/usr/bin/env python3

# as simple function
def myFunction(a):
  return a**2

# intVar+5                is just a short for
# intVar.__add__(5)
intVar = 10
print("using __add__() : ", intVar+5, intVar.__add__(5))
print()

print("*******************")
print("content of dir(int)")
print("*******************")
print()
for mF in dir(int):     # dir: directory of magic methods
  print(mF)

print()
print("**************************")
print("content of dir(myFunction)")
print("**************************")
print()
for mF in dir(myFunction):  
  print(mF)

built-in functions

A
abs()
aiter()
all()
any()
anext()
ascii()

B
bin()
bool()
breakpoint()
bytearray()
bytes()

C
callable()
chr()
classmethod()
compile()
complex()

D
delattr()
dict()
dir()
divmod()

E
enumerate()
eval()
exec()

F
filter()
float()
format()
frozenset()

G
getattr()
globals()

H
hasattr()
hash()
help()
hex()

I
id()
input()
int()
isinstance()
issubclass()
iter()
__import__()
L
len()
list()
locals()

M
map()
max()
memoryview()
min()

N
next()

O
object()
oct()
open()
ord()

P
pow()
print()
property()
R
range()
repr()
reversed()
round()

S
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()

T
tuple()
type()

V
vars()

Z
zip()


threading






Copy Copy to clipboad
Downlaod Download
#!/usr/bin/env python3

import threading    # omen est nomen
import time

class DeltaT:
 myTime = time.perf_counter()
 def diff():
   newTime = time.perf_counter()
   deltaTime = newTime - DeltaT.myTime
   DeltaT.myTime = newTime
   return deltaTime


def taskFunction(name):
  print(f'Thread {name:2d}: starting')
  time.sleep(3)
  print(f'Thread {name:2d}: finishing')


# blocks out-of-us access
if __name__ == "__main__":

  print(DeltaT.diff())
  print(f'Main  {DeltaT.diff():4.2f}  : before creating thread')
  x = threading.Thread(target=taskFunction, args=(1,))
  print(f'Main  {DeltaT.diff():4.2f}  : before running the thread')

  time.sleep(2)
  x.start()                  # can be started anywhere

  print(f'Main  {DeltaT.diff():4.2f}  : waiting for the thread to finish')
  x.join()                   # stop until thread is done
  print(f'Main  {DeltaT.diff():4.2f}  : all done')

timer objects

Copy Copy to clipboad
Downlaod Download
#!/usr/bin/env python3

import time                # time manipulation, sleeping
import threading as thr    # threading
 
# a random target task function
def taskFuntion(message):
#   time.sleep(3.0)                           # test it
    print(message)
 
#
# thread timer object invokes a task function with arguments
#
timer = thr.Timer(3, taskFuntion, args=('timer function executed',))
timer.start()

# counting while waiting for the timer to finish
counting = 0
while (timer.is_alive()):                     # try with 'not'
  time.sleep(0.3)                             # sleeping in seconds
  counting += 1
  print("counting while waiting ", counting)

# cancel the thread
if (timer.is_alive()):
  print('canceling the timer')
  timer.cancel()

performance measurement

Copy Copy to clipboad
Downlaod Download
#!/usr/bin/env python3

import math
import time

# times in seconds since last call
class DeltaT:
 myTime = time.perf_counter()
 def diff():
   newTime = time.perf_counter()
   deltaTime = newTime - DeltaT.myTime
   DeltaT.myTime = newTime
   return deltaTime

print(time.perf_counter())
print()
print(DeltaT.diff())
for i in range(int(1e7)):
  pow(math.log(i+1.0,10),math.log(i+1.0,10))
print(DeltaT.diff(), " time used (in secconds)")