Describing several commands and methods that will be used throughout the simulations
Note: Basic knowledge of programming languages and concepts is assumed. Only specific concepts that are different from, e.g., C++ or Matlab, are provided.
NOTE 2: The following summary is by no means complete or exhaustive, but only provides a short and simplified overview of the commands used throughout the simulations in the lecture. For a detailed introduction please have a look at one of the numerous web-tutorials or books on Python, e.g.,
In [1]:
# defining lists
sport_list = [ 'cycling', 'football', 'fitness' ]
first_prime_numbers = [ 2, 3, 5, 7, 11, 13, 17, 19 ]
# getting contents
sport = sport_list[ 2 ]
third_prime = first_prime_numbers[ 2 ]
# printing
print( 'All sports:', sport_list )
print( 'Sport to be done:', sport )
print( '\nFirst primes:', first_prime_numbers )
print( 'Third prime number:', third_prime )
In [2]:
# adapt entries and append new entries
sport_list[ 1 ] = 'swimming'
sport_list.append( 'running' )
first_prime_numbers.append( 23 )
# printing
print( 'All sports:', sport_list )
print( 'First primes:', first_prime_numbers )
In [3]:
# defining tuple
sport_tuple = ( 'cycling', 'football', 'fitness' )
# getting contents
sport = sport_tuple[ 2 ]
# printing
print( 'All sports:', sport_tuple )
print( 'Sport to be done:', sport )
In [4]:
# append new entries
sport_tuple += ( 'running', )
# printing
print( 'All sports:', sport_tuple )
print()
# changing entries will fail
# --> ERROR is being generated on purpose
# --> NOTE: Error is handled by 'try: ... except: ...' statement
try:
sport_tuple[ 1 ] = 'swimming'
except:
print('ERROR: Entries within tuples cannot be adapted!')
dict or by curly brackets with entities of shape "key : value" being separated by comma
In [5]:
# defining dictionaries
sports_days = { 'Monday': 'pause', 'Tuesday': 'fitness', 'Wednesday' : 'running',
'Thursday' : 'fitness', 'Friday' : 'swimming', 'Saturday' : 'cycling',
'Sunday' : 'cycling' }
print( 'Sport by day:', sports_days )
print( '\nOn Tuesday:', sports_days[ 'Tuesday' ])
In [6]:
# Changes are made by using the key as identifier
sports_days[ 'Tuesday' ] = 'running'
print( 'Sport by day:', sports_days )
In [7]:
# defining sets
sports_set = { 'fitness', 'running', 'swimming', 'cycling'}
print( sports_set )
print()
# indexing will fail
# --> ERROR is being generated on purpose
try:
print( sports_set[0] )
except:
print('ERROR: No indexing of sets!')
In [8]:
# adding elements (or not)
sports_set.add( 'pause' )
print(sports_set)
sports_set.add( 'fitness' )
print(sports_set)
In [9]:
# union of sets (also: intersection, complement, ...)
all_stuff_set = set( sports_set )
union_of_sets = all_stuff_set.union( first_prime_numbers)
print( union_of_sets )
In [10]:
# looping in lists simply parsing along the list
for s in sport_list:
print( s )
print()
# looping in dictionaries happens along keys
for s in sports_days:
print( '{}: \t{}'.format( s, sports_days[ s ] ) )
In [11]:
# initialize variables
sum_primes = 0
_n = 0
# sum primes up to sum-value of 20
while sum_primes < 20:
# add prime of according index
sum_primes += first_prime_numbers[ _n ]
# increase index
_n += 1
print( 'Sum of first {} primes is {}.'.format( _n, sum_primes ) )
In [12]:
def get_n_th_prime( n, first_prime_numbers ):
'''
DOC String
IN: index of prime number, list of prime numbers
OUT: n-th prime number
'''
# do something smart as, e.g., checking that according index really exists
# "assert" does the job by checking first arg and--if not being TRUE--providing text given as second arg
try:
val = first_prime_numbers[ n - 1 ]
except:
return '"ERROR: Index not feasible!"'
# NOTE: since counting starts at 0, (n-1)st number is returned
# Furthermore, there is no need for a function here; a simple reference would have done the job!
return first_prime_numbers[ n - 1 ]
# show doc string
print( help( get_n_th_prime ) )
# apply functions
N = 3
print( '{}. prime number is {}.'.format( N, get_n_th_prime( N, first_prime_numbers ) ) )
print()
N = 30
print( '{}. prime number is {}.'.format( N, get_n_th_prime( N, first_prime_numbers ) ) )
import: importing modules to be used as, e.g., modules for matplotlib), numpy), np.linalg: linear algebranp.random: everything dealing with randomness, as, e.g., realization of different distributionsscipy),itertools, ...)break: quitting current loopcontinue: processing to next iteration of current loopenumerate( x ): generates enumeration tuples of shape ( index, value ) parsing all entries of iterable xlen( x ): length of list/tuple xrange( N ): generates iterable with integers $0,\ldots N-1$np.arange( a, b, step ): generating a numpy array starting at a (included) up to b (not included) with step size 'step' (optional)np.argmax( a ): returns first index at which a attains its maximum valuenp.array( ): standard data type of numpy, essentially correponding to a vector as used in mathsnp.average( x ): determines average value of list/array xnp.concatenate( x, y ): generates new vector/tuple ( x, y )x.copy( ): creates a copy of xnp.corrcoeff( x, y ): determines correlation coefficient of x and ynp.correlate( x, y, 'full'): determines correlation function (!) of vectors (signals) x and ynp.cumsum( x ): cumulative sum of xnp.histogram( values, bins ): generates histogram (relative frequency) of 'values' with respect to classes listed in 'bins'np.isclose( a, b ): returns Boolean describing if $a \approx b$ 'within tolerance'np.linspace( a, b, num_points ): generates vector of 'num_points' equidistant points in $[a, b)$np.ones( shape ): generates array of ones of shape 'shape'np.ones_like( x ): generates array of ones of same shape and type as xnp.prod( x ): multiplying all elements of xnp.random.choice( A, size = S ): sampling S entities out of A; replacing elements and probability may be characterized as parametersnp.random.rand( size ): generates 'size' random values being uniformly distributed in $[0,1)$np.random.randint( a, b, size ): generates 'size' random integers between a (included) and b (not included)np.random.randn( size ): generates a vector of standard gaussian ($E(X)=0, D^2(X)=1$) random variables of size 'size'np.sum( x ): summing up all elements of xnp.zeros( shape ): generates array of zeros of shape 'shape'np.zeros_like( x ): generates array of zeros of same shape and type as x