markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Mangelfulle spørringer mot NVDB api V3? her sammenligner vi resultatet av spørringen `/vegobjekter/904?kommune=5001&veg(system)referanse=K` mot NVDB api V2 og V3.
import json import pandas as pd import os mappe = 'stavanger_904' filer = os.listdir(mappe) manglergeom = [] fasit = [] etterspurt_E = [] etterspurt_R = [] etterspurt_F = [] etterspurt_K = [] etterspurt_P = [] etterspurt_S = [] for eifil in filer: if 'json' in eifil: spurt_vegkat = eifil.split(...
_____no_output_____
MIT
debug_nvdbapilesv3/vegobjekter/sjekkmangler.ipynb
LtGlahn/diskusjon_diverse
Har vi duplikater i de ugyldige V3-objektene?
duplikat = manglergeom[ manglergeom.duplicated(subset='id', keep=False) ] print( len( duplikat), 'duplikater av', len( manglergeom), 'ugyldige og', len(fasit), 'totalt')
4 duplikater av 155 ugyldige og 5648 totalt
MIT
debug_nvdbapilesv3/vegobjekter/sjekkmangler.ipynb
LtGlahn/diskusjon_diverse
Relativt uinteressant, iallfall inntil videre Lær mer om ugyldige data Stemmer ønsket vegkategori med det vi fant?
mangler = pd.merge( left=manglergeom, right=fasit, left_on='id', right_on='vegobjektid', how='inner') mangler.columns mangler[ mangler['spurt_vegkat_x'] == mangler['vegkat']]
_____no_output_____
MIT
debug_nvdbapilesv3/vegobjekter/sjekkmangler.ipynb
LtGlahn/diskusjon_diverse
Er det en vegkategori som peker seg ut?
mangler.vegkat.value_counts()
_____no_output_____
MIT
debug_nvdbapilesv3/vegobjekter/sjekkmangler.ipynb
LtGlahn/diskusjon_diverse
Estimate Paramters of system of ODEs for given time course data imports
import pandas as pd # convert excel to dataframe import numpy as np # convert dataframe to nparray for solver from scipy.integrate import odeint # solve ode from lmfit import minimize, Parameters, Parameter, report_fit # fitting import matplotlib.pyplot as plt # plot data and results
_____no_output_____
BSD-2-Clause
Model_Stephan_pH7.ipynb
HannahDi/EnzymeML_KineticModeling
Get data from excel
data = './datasets/Stephan_pH7.xlsx' df = pd.read_excel(data, sheet_name=1)
_____no_output_____
BSD-2-Clause
Model_Stephan_pH7.ipynb
HannahDi/EnzymeML_KineticModeling
Convert dataframe to np-array
# time: data_time = df[df.columns[0]].to_numpy(np.float64) #shape: (60,) # substrate data (absorption): data_s = np.transpose(df.iloc[:,1:].to_numpy(np.float64)) #shape: (3, 60)
_____no_output_____
BSD-2-Clause
Model_Stephan_pH7.ipynb
HannahDi/EnzymeML_KineticModeling
Fit data to system of odes define the ode functions
def f(w, t, paras): ''' System of differential equations Arguments: w: vector of state variables: w = [v,s] t: time params: parameters ''' v, s = w try: a = paras['a'].value vmax = paras['vmax'].value km = paras['km'].value except KeyErro...
_____no_output_____
BSD-2-Clause
Model_Stephan_pH7.ipynb
HannahDi/EnzymeML_KineticModeling
Solve ODE
def g(t, w0, paras): ''' Solution to the ODE w'(t)=f(t,w,p) with initial condition w(0)= w0 (= [v0, s0]) ''' w = odeint(f, w0, t, args=(paras,)) return w
_____no_output_____
BSD-2-Clause
Model_Stephan_pH7.ipynb
HannahDi/EnzymeML_KineticModeling
compute residual between actual data (s) and fitted data
def res_multi(params, t, data_s): ndata, nt = data_s.shape resid = 0.0*data_s[:] # residual per data set for i in range(ndata): w0 = params['v0'].value, params['s0'].value model = g(t, w0, params) # only have data for s not v s_model = model[:,1] s_model_b = s_mod...
_____no_output_____
BSD-2-Clause
Model_Stephan_pH7.ipynb
HannahDi/EnzymeML_KineticModeling
Bringing everything togetherInitialize parameters
# initial conditions: v0 = 0 s0 = np.mean(data_s,axis=0)[0] # Set parameters including bounds bias = 0.1 params = Parameters() params.add('v0', value=v0, vary=False) params.add('s0', value=s0-bias, min=0.1, max=s0) params.add('a', value=1., min=0.0001, max=2.) params.add('vmax', value=0.2, min=0.0001, max=1.) params.a...
_____no_output_____
BSD-2-Clause
Model_Stephan_pH7.ipynb
HannahDi/EnzymeML_KineticModeling
Fit model and visualize results
# fit model result = minimize(res_multi , params, args=(t_measured, data_s), method='leastsq') # leastsq nelder report_fit(result) # plot the data sets and fits w0 = params['v0'].value, params['s0'].value data_fitted = g(t_measured, w0, result.params) plt.figure() for i in range(data_s.shape[0]): plt.plot(t_measu...
[[Fit Statistics]] # fitting method = leastsq # function evals = 96 # data points = 180 # variables = 5 chi-square = 0.04123983 reduced chi-square = 2.3566e-04 Akaike info crit = -1498.63538 Bayesian info crit = -1482.67059 [[Variables]] v0: 0 (fixed) ...
BSD-2-Clause
Model_Stephan_pH7.ipynb
HannahDi/EnzymeML_KineticModeling
Hyper-parameter tuning **Learning Objectives**1. Understand various approaches to hyperparameter tuning2. Automate hyperparameter tuning using AI Platform HyperTune IntroductionIn the previous notebook we achieved an RMSE of **4.13**. Let's see if we can improve upon that by tuning our hyperparameters.Hyperparameters ...
# Ensure that we have Tensorflow 1.13 installed. !pip3 freeze | grep tensorflow==1.13.1 || pip3 install tensorflow==1.13.1 PROJECT = "qwiklabs-gcp-636667ae83e902b6" # Replace with your PROJECT BUCKET = "qwiklabs-gcp-636667ae83e902b6_al" # Replace with your BUCKET REGION = "us-east1" # Choose an available ...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/03_model_performance/labs/d_hyperparameter_tuning.ipynb
aleistra/training-data-analyst
Move code into python packageLet's package our updated code with feature engineering so it's AI Platform compatible.
%%bash mkdir taxifaremodel touch taxifaremodel/__init__.py
mkdir: cannot create directory ‘taxifaremodel’: File exists
Apache-2.0
courses/machine_learning/deepdive/03_model_performance/labs/d_hyperparameter_tuning.ipynb
aleistra/training-data-analyst
Create model.pyNote that any hyperparameters we want to tune need to be exposed as command line arguments. In particular note that the number of hidden units is now a parameter.
%%writefile taxifaremodel/model.py import tensorflow as tf import numpy as np import shutil print(tf.__version__) #1. Train and Evaluate Input Functions CSV_COLUMN_NAMES = ["fare_amount","dayofweek","hourofday","pickuplon","pickuplat","dropofflon","dropofflat"] CSV_DEFAULTS = [[0.0],[1],[0],[-74.0],[40.0],[-74.0],[40....
Overwriting taxifaremodel/model.py
Apache-2.0
courses/machine_learning/deepdive/03_model_performance/labs/d_hyperparameter_tuning.ipynb
aleistra/training-data-analyst
Create task.py **Exercise 1**The code cell below has two TODOs for you to complete. Firstly, in model.py above we set the number of hidden units in our model to be a hyperparameter. This means `hidden_units` must be exposed as a command line argument when we submit our training job to Cloud ML Engine. Modify the code...
%%writefile taxifaremodel/task.py import argparse import json import os from . import model if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--hidden_units", help = "Hidden layer sizes to use for DNN feature columns -- provide space-separated layers", ...
Overwriting taxifaremodel/task.py
Apache-2.0
courses/machine_learning/deepdive/03_model_performance/labs/d_hyperparameter_tuning.ipynb
aleistra/training-data-analyst
Create hypertuning configuration We specify:1. How many trials to run (`maxTrials`) and how many of those trials can be run in parrallel (`maxParallelTrials`) 2. Which algorithm to use (in this case `GRID_SEARCH`)3. Which metric to optimize (`hyperparameterMetricTag`)4. The search region in which to constrain the hype...
%%writefile hyperparam.yaml trainingInput: scaleTier: BASIC hyperparameters: goal: MINIMIZE maxTrials: 5 maxParallelTrials: 5 hyperparameterMetricTag: rmse enableTrialEarlyStopping: True algorithm: GRID_SEARCH params: - parameterName: hidden_units type: CATEGORICAL catego...
Overwriting hyperparam.yaml
Apache-2.0
courses/machine_learning/deepdive/03_model_performance/labs/d_hyperparameter_tuning.ipynb
aleistra/training-data-analyst
Run the training job|Same as before with the addition of `--config=hyperpam.yaml` to reference the file we just created.This will take about 20 minutes. Go to [cloud console](https://console.cloud.google.com/mlengine/jobs) and click on the job id. Once the job is completed, the choosen hyperparameters and resulting ob...
OUTDIR="gs://{}/taxifare/trained_hp_tune".format(BUCKET) !gsutil -m rm -rf {OUTDIR} # start fresh each time !gcloud ai-platform jobs submit training taxifare_$(date -u +%y%m%d_%H%M%S) \ --package-path=taxifaremodel \ --module-name=taxifaremodel.task \ --config=hyperparam.yaml \ --job-dir=gs://{BUCKET}/t...
Removing gs://qwiklabs-gcp-636667ae83e902b6_al/taxifare/trained_hp_tune/1/export/exporter/#1563484245754874... Removing gs://qwiklabs-gcp-636667ae83e902b6_al/taxifare/trained_hp_tune/1/events.out.tfevents.1563484194.cmle-training-731225091109210751#1563484432093881... Removing gs://qwiklabs-gcp-636667ae83e902b6_al/taxi...
Apache-2.0
courses/machine_learning/deepdive/03_model_performance/labs/d_hyperparameter_tuning.ipynb
aleistra/training-data-analyst
ResultsThe best result is RMSE **4.02** with hidden units = 128,64,32. This improvement is modest, but now that we have our hidden units tuned let's run on our larger dataset to see if it helps. Note the passing of hyperparameter values via command line
OUTDIR="gs://{}/taxifare/trained_large_tuned".format(BUCKET) !gsutil -m rm -rf {OUTDIR} # start fresh each time !gcloud ai-platform jobs submit training taxifare_large_$(date -u +%y%m%d_%H%M%S) \ --package-path=taxifaremodel \ --module-name=taxifaremodel.task \ --job-dir=gs://{BUCKET}/taxifare \ --pytho...
Removing gs://qwiklabs-gcp-636667ae83e902b6_al/taxifare/trained_large_tuned/events.out.tfevents.1563484096.cmle-training-worker-285c128a20-0-kn9fp#1563485144189527... Removing gs://qwiklabs-gcp-636667ae83e902b6_al/taxifare/trained_large_tuned/#1563485147333149... Removing gs://qwiklabs-gcp-636667ae83e902b6_al/taxifare/...
Apache-2.0
courses/machine_learning/deepdive/03_model_performance/labs/d_hyperparameter_tuning.ipynb
aleistra/training-data-analyst
An Introduction to *Python*Let us begin by checking the version of our Python interpreter.
import sys sys.version
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
This notebook gives a short introduction to *Python*. We will start with the basics but as the **main goal** of this introduction is to show how *Python* supports *sets* we will quickly move to more advanced topics.In order to show off the features of *Python* we will give some examples that are not fully explained at...
1 + 2
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
In *Python*, the precision of integers is not bounded. Hence, the following expression does **not** causean integer overflow.
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 * 21 * 22 * 23 * 24 * 25
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The next *cell* in this notebook shows how to compute the *factorial* of 1000, i.e. it shows how to compute the product$$ 1000! = 1 \cdot 2 \cdot 3 \cdot {\dots} \cdot 998 \cdot 999 \cdot 1000 $$It uses some advanced features from *functional programming* that will be discussed later.
import functools functools.reduce(lambda x, y: (x*y), range(1, 1000+1))
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The following command will stop the interpreter if executed. It is not useful inside a *Jupyter* notebook. Hence, the next line should not be evaluated. However, if you evaluate the following line, nothing bad will happen as the interpreter is just restarted by *Jupyter*.
exit()
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
In order to write something to the screen, we can use the function print. This function can print objects of any type. In the following example, this function prints a string. In *Python* any character sequence enclosed in single quotes is string.
print('Hello, World!')
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The last expression in every notebook cell is automatically printed.
'Hello, World!'
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
If we want to supress the last expression from being printed, we can end the expression with a semicolon:
'Hello, World!';
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Instead of using single quotes we can also use double quotes as seen in the next example. However, the convention is to use single quotes, unless the string itself contains a single quote.
"Hello, World!"
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The function print accepts any number of arguments. For example, to print the string "36 * 37 / 2 = " followed by the value of the expression $36 \cdot 37 / 2$ we can use the following print statement:
print('36 * 37 / 2 =', 36 * 37 // 2)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
In the expression "36 \* 37 // 2" we have used the operator "//" in order to enforce *integer division*. If we had used the operator "/" instead, *Python* would have used *floating point division* and therefore it would have printed the floating point number 666.0 instead of the integer 666.
print('36 * 37 / 2 =', 36 * 37 / 2) 5 // 3, 5 % 3 range(1, 9+1) A = set(range(1, 9+1)) A
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The function `sum` can be used to some up all elements of a set (or a list).
sum(A)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The following script reads a natural number $n$ and computes the sum $\sum\limits_{i=1}^n i$. The function input prompts the user to enter a string. This string is then converted into an integer using the function int. Next, the set S is created such that $$\texttt{s} = \{1, \cdots, n\}. $$ ...
n = input('Type a natural number and press return: ') n = int(n) S = set(range(1, n+1)) print('The sum 1 + 2 + ... + ', n, ' is equal to ', sum(S), '.', sep='')
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
If we input $36$, which happens to be equal to $6^2$ above, then we discover the following remarkable identity:$$ \sum\limits_{i=1}^{6^2} i = 666. $$ The following example shows how *functions* can be defined in *Python*. The function $\texttt{sum}(n)$ is supposed to compute the sum of all the numbers in the set $\{1,...
def sum(n): if n == 0: return 0 return sum(n-1) + n sum sum(3) def sum(n): print(f'calling sum({n})') if n == 0: print('sum(0) = 0') return 0 snm1 = sum(n-1) print(f'sum({n}) = sum({n-1}) + {n} = {snm1} + {n} = {snm1 + n}') return snm1 + n sum(3)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Let us discuss the implementation of the function sum line by line: The keyword def starts the definition of the function. It is followed by the name of the function that is defined. The name is followed by the list of the parameters of the function. This list is enclosed in parentheses. If there had been more th...
n = int(input("Enter a natural number: ")) total = sum(n) if n > 2: print("0 + 1 + 2 + ... + ", n, " = ", total, sep='') else: print(total)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Sets in *Python* *Python* supports sets as a **native** datatype. This is one of the reasons that have lead me to choose *Python* as the programming language for this course. To get a first impression how sets are handled in *Python*, let us define two simple sets $A$ and $B$ and print them:
A = {1, 2, 3} B = {2, 3, 4} print(f'A = {A}, B = {B}')
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
There is a caveat here, we cannot define the empty set using the expression {} since this expression creates the empty dictionary instead. (We will discuss the data type of *dictionaries* later.) To define the empty set $\emptyset$, we therefore have to use the following expression:
S = set() S
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Note that the empty set is also printed as set() in *Python* and not as {}. Next, let us compute the union $A \cup B$. This is done using the operator "|".
A | B
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
To compute the intersection $A \cap B$, we use the operator "&":
A & B
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The set difference $A \backslash B$ is computed using the operator "-":
A - B, B - A
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
It is easy to test whether $A$ is a subset of $B$, i.e. whether $A \subseteq B$ holds:
A <= B
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Testing whether an object $x$ is an element of a set $M$, i.e. to test whether $x \in M$ holds, is straightforward:
1 in A
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
On the other hand, the number $1$ is not an element of the set $B$, i.e. we have $1 \not\in B$:
1 not in B
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
It is important to know that sets are not ordered. The reason is that sets are implemented as hash tables. We discuss hash tables in the lecture on algorithms in the second semester.
print({-1,2,-3,4})
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
However, if a set is displayed by a **Jupyter notebook** without a print statement, the elements are sorted.
{-1,2,-3,4}
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Defining Sets via Selection and Images Remember how we can define subsets of a given set $M$ via the axiom of selection. If $p$ is a property such that for any object $x$ from the set $M$ the expression $p(x)$ is either True or False, the subset of all those elements of $M$ such that $p(x)$ is True can be defined a...
M = set(range(1, 100+1)) { x for x in M if x % 7 == 0 }
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
In general, in *Python* the set$$ \{ x \in M \mid p(x) \} $$is computed by the expression$$ \{\; x\; \texttt{for}\; x\; \texttt{in}\; M\; \texttt{if}\; p(x)\; \}. $$This is called a *set comprehension*.*Image* sets can be computed in a similar way. If $f$ is a function defined for all elements of a set $M$, the image ...
M = set(range(1,10+1)) { x*x for x in M }
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The computation of image sets and selections can be *combined.* If $M$ is a set, $p$ is a property such that $p(x)$ is either True or False for elements of $M$, and $f$ is a function such that $f(x)$ is defined for all $x \in M$ then we can compute set $$ \{ f(x) \mid x \in M \wedge p(x) \} $$of all images $f(x)$ fro...
{ x*x for x in M if x % 2 == 0 }
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
We can iterate over more than one set. For example, let us define the set of all products $p \cdot q$ of numbers $p$ and $q$ from the set $\{2, \cdots, 10\}$, i.e. we intend to define the set$$ \bigl\{ p \cdot q \bigm| p \in \{2,\cdots,10\} \wedge q \in \{2,\cdots,10\} \bigr\}. $$In *Python*, this set is defined as fo...
{ p * q for p in range(2, 6+1) for q in range(2, 6+1) }
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
We can use this set to compute the set of *prime numbers*. After all, the set of prime numbers is the set of all those natural numbers bigger than $1$ that can not be written as a proper product, that is a number $x$ is *prime* if $x$ is bigger than $1$ and there are no natural numbers $p$ and $q$ both bigge...
S = set(range(2, 100+1)) print(S - { p * q for p in S for q in S })
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
An alternative way to compute primes works by noting that a number $p$ is prime iff there is no number $t$ that is different from both $1$ and $p$ and, furthermore, divides the number $p$. The function `dividers` given below computes the set of all numbers dividing a given number $p$ evenly:
def dividers(p): ''' Compute the set of numbers that divide the number p. This is just an auxiliary function. ''' return { t for t in range(1, p+1) if p % t == 0 } dividers(20) n = 100 primes = { p for p in range(2, n) if dividers(p) == {1, p} } print(primes)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Computing the Power Set Unfortunately, there is no operator to compute the power set $2^M$ of a given set $M$. Since the power set is needed frequently, we have to implement a function power to compute this set ourselves. The easiest way to compute the power set $2^M$ of a set $M$ is to implement the following recur...
{{1,2}, {2,3}} {frozenset({1,2}), frozenset({2,3})}
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The reason we got the error when trying to evaluate the expression``` {{1,2}, {2,3}}``` is that in *Python* sets are implemented via *hash tables* and therefore the elements of a set need to be *hashable*. (The notion of a *hash table* will be discussed in more detail in the lecture on *Algorithms*.) However, sets ar...
def power(M): "This function computes the power set of the set M." if M == set(): return { frozenset() } else: C = set(M) # C is a copy of M as we don't want to change the set M x = C.pop() # pop removes some element x from the set C P1 = power(C) P2 = { A | {x} fo...
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Let us print this in a more readable way. To this end we implement a function prettify that turns a set of frozensets into a string that looks like a set of sets.
def prettify(M): """Turn the set of frozen sets M into a string that looks like a set of sets. M is assumed to be the power set of some set. """ result = "{{}, " # The empty set is always an element of a power set. for A in M: if A == set(): # The empty set has already been taken care o...
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The function $S\texttt{.add}(x)$ insert the element $x$ into the set $S$.
S = {1, 2, 3} S.add(4) S
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
In *Python*, variables are references and assignments do not copy values. Instead, they just create new references to the old values! This is the reason that below both A and B change their value, even so it seems that we only change A.
A = {1,2,3} B = A A.add(4) print(f'A = {A}') print(f'B = {B}')
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
In order to prevent this behaviour, we have to make a copy of the set A. This can be done by calling the function $\texttt{set}(\texttt{A})$.
A = {1,2,3} B = set(A) A.add(4) print(f'A = {A}') print(f'B = {B}')
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Pairs and Cartesian Products In *Python*, pairs can be created by enclosing the components of the pair in parentheses. For example, to compute the pair $\langle 1, 2 \rangle$ we can write:
(1, 2)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
It is not even necessary to enclose the components of a pair in parentheses. For example, to compute the pair $\langle 1, 2 \rangle$ we can also use the following expression:
1, 2
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The Cartesian product $A \times B$ of two sets $A$ and $B$ can now be computed via the following expression:$$ \{\; (x, y) \;\texttt{for}\; x \;\texttt{in}\; A\; \texttt{for}\; y\; \texttt{in}\; B\; \} $$ For example, as we have defined $A$ as $\{1,2,3\}$ and $B$ as $\{4,5\}$, the Cartesian product of $A$ and $B$ is co...
A = {1, 2, 3} B = {4, 5} { (x, y) for x in A for y in B }
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Tuples *Tuples* are a generalization of pairs. For example, to compute the tuple $\langle 1, 2, 3 \rangle$ we can use the following expression:
(1, 2, 3)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Tuples are not sets, the order of the elements matters:
(1, 2, 3) != (2, 3, 1)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Longer tuples can be build using the function range in combination with the function tuple:
tuple(range(1, 10+1))
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Tuple can be *concatenated* using the operator +:
T1 = (1, 2, 3) T2 = (4, 5, 6) T3 = T1 + T2 T3
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The *length* of a tuple is computed using the function len:
len(T3)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The components of a tuple can be extracted using square brackets. Note, that the first component of a tuple has the index $0$! This is similar to the behaviour of *arrays* in the programming language C.
print("T3[0] =", T3[0]) print("T3[1] =", T3[1]) print("T3[2] =", T3[2])
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
If we use negative indices, then we index from the back of the tuple, as shown in the following example:
print(f'T3[-1] = {T3[-1]}') # last element print(f'T3[-2] = {T3[-2]}') # penultimate element print(f'T3[-3] = {T3[-3]}') # antepenultimate element T3
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The slicing operator extracts a subtuple from a given tuple. If $L$ is a tuple and $a$ and $b$ are natural numbers such that $a \leq b$ and $a,b \in \{0, \texttt{len}(L) \}$, then the syntax of the slicing operator is as follows:$$ L[a:b] $$The expression $L[a:b]$ extracts the subtuple that starts with the element $L[...
L = tuple(range(1,10+1)) print(f'L = {L}, L[2:6] = {L[2:6]}')
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Slicing works with negative indices, too:
L[2:-2]
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Slicing also works for strings.
s = 'abcdef' s[2:-2]
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
If we want to create a tuple of length $1$, we have to use the following syntax:
L = (1,) L
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Note that above the comma is **not** optional as the expression $(1)$ would be interpreted as the number $1$. Similar to working with sets, it is often convenient to build long tuples using *comprehensions*.In order to create all square numbers that are odd and $\leq$ 100 we can do the following:
G = (x*x for x in range(10+1) if x % 2 == 1) G
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Above, `G` is a *generator object*. To turn this into a tuple we use the predefined function `tuple`:
tuple(G)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Lists Next, we discuss the data type of lists. Lists are a lot like tuples, but in contrast to tuples, lists are mutatable, i.e. we can change lists. To construct a list, we use square backets:
L = [1, 2, 3] L
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
In a list, the order of the elements does matter:
[1, 2, 3] == [3, 2, 1]
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The *index operator* $[\cdot]$ is a postfix operator that is used to return the element that is stored at a given index in a list.
L[0]
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
To change the first element of a list, we can use the *index operator* on the left hand side of an assignment:
L[0] = 7 L
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
This last operation would not be possible if L had been a tuple instead of a list.Lists support concatenation in the same way as tuples:
[1,2,3] + [4,5,6]
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The function `len` computes the length of a list:
len([4,5,6])
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Lists support the functions max and min. The expression $\texttt{max}(L)$ computes the maximum of all the elements of the list (or tuple) $L$, while $\texttt{min}(L)$ computes the smallest element of $L$. These functions also operate on tuples or sets. They even work on list of lists or set of frozensets, but this i...
max([1,2,3]) min([1,2,3]) max({1,2,3}) max([[1,2], [2,3,4], [5]]) max({frozenset({1,2}), frozenset({2,3,4}), frozenset({5})})
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Boolean Values and Boolean Operators In *Python*, the *truth values*, also known as *Boolean values*, are written as True and False.
True False
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The following function is needed for pretty-printing. It assumes that the argument val is a truth value. This truth value is then turned into a string that has a size of exactly 5 characters.
def toStr(val): if val: return 'True ' return 'False'
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
These values can be combined using the Boolean operators $\wedge$, $\vee$, and $\neg$. In *Python*, these operators are denoted as `and`, `or`, and `not`. The following table shows how the operator `and` is defined:
B = (True, False) for x in B: for y in B: print(toStr(x), 'and', toStr(y), '=', x and y)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The *disjunction* of two Boolean values is only *False* if both values are *False*:
for x in B: for y in B: print(toStr(x), 'or', toStr(y), '=', x or y)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Finally, the negation operator works as expected:
for x in B: print('not', toStr(x), '=', not x)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Boolean values are created by comparing numbers using the follwing comparison operators: $a\;\texttt{==}\;b$ is true iff $a$ is equal to $b$. $a\;\texttt{!=}\;b$ is true iff $a$ is different from $b$. $a\;\texttt{ $a\;\texttt{ $a\;\texttt{>=}\;b$ is true iff $a$ is bigger than or equal to $b$. $a\;\te...
1 == 2 1 != 2 1 < 2 1 <= 2 1 > 2 1 >= 2
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Comparison operators can be chained as shown in the following example:
1 < 2 > -1
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
*Python* supports the universal quantifier $\forall$. If $L$ is a list of Boolean values, then we can check whether all elements of $L$ are True by writing$$ \texttt{all}(L). $$For example, to check whether all elements of a list $L$ are even we can write the following:
L = [2, 4, 6, 7] all(x % 2 == 0 for x in L)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
*Python* also supports the existential quantifier $\exists$. If $L$ is a list of Boolean values, the expression$$ \texttt{any}(L) $$is true iff there exists an element $x \in L$ such that $x$ is true.
any(x ** 2 > 2 ** x for x in range(1,4+1))
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Control Structures First of all, *Python* supports *branching*. The following example is taken from the *Python* tutorial at [https://python.org](https://docs.python.org/3/tutorial/controlflow.html):
x = int(input("Please enter an integer: ")) if x < 0: print('The number is negative!') elif x == 0: print('The number is zero.') elif x == 1: print("It's a one.") else: print("It's more than one.")
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
*Loops* can be used to iterate over sets, lists, tuples, or generators. The following example prints the numbers from 1 to 10.
for x in range(1, 10+1): print(x)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The same can be achieved with a `while` loop:
x = 1 while x <= 10: print(x, end=' ') x += 1
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The following program computes the prime numbers according to an[algorithm given by Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). 1. We set $n$ equal to 100 as we want to compute the set all prime numbers less or equal that 100. 2. `primes` is the list of numbers from 0 upto $n$, i.e. we have init...
n = 100 primes = list(range(0, n+1)) primes[1] = 0 for i in range(2, n+1): for j in range(2, n+1): if i * j <= n: primes[i * j] = 0 print(primes) print({ i for i in range(2, n+1) if primes[i] != 0 })
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The algorithm given above can be improved by using the following observations: 1. If a number $x$ can be written as a product $a \cdot b$, then at least one of the numbers $a$ or $b$ has to be less than $\sqrt{x}$. Therefore, the `for` loop in line 5 below iterates as long as $i \leq \sqrt{x}$. The function `...
%%time from math import sqrt, ceil n = 1000000 primes = list(range(n+1)) for i in range(2, ceil(sqrt(n))): if primes[i] == 0: continue j = i while i * j <= n: primes[i * j] = 0 j += 1 P = { i for i in range(2, n+1) if primes[i] != 0 } print(sorted(list(P)))
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Numerical Functions *Python* provides all of the mathematical functions that you learned at school. A detailed listing of these functions can be found at [https://docs.python.org/3.6/library/math.html](https://docs.python.org/3.6/library/math.html). We just show the most important functions and constants. In order ...
import math
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The mathematical constant [Pi](https://en.wikipedia.org/wiki/Pi) which is most often written as $\pi$ is available as `math.pi`.
math.pi
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The sine function is called as follows:
math.sin(math.pi/6)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The cosine function is called as follows:
math.cos(0.0)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The tangent function is called as follows:
math.tan(math.pi/4)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The *arc sine*, *arc cosine*, and *arc tangent* are called by prefixing the character `'a'` to the name of the function as seen below:
math.asin(1.0) math.acos(1.0) math.atan(1.0)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Euler's number $e$ can be computed as follows:
math.e
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic