NTNUs Python-on-exam
Skriv inn/rediger koden og trykk på “Run Code”.
Trykk på AddNewCodeBlock for å få til et nytt tomt kodevindu.
Trykk på Kopi-symbolet for å kopiere koden til buffer (og seinere inn i Inspera).
Har du for mange/for store/for trege kodevinduer – last ned denne siden på nytt. Alt av din gammel kode forsvinner da – sjekk at du har overført den viktige koden til Inspera.
Keywords
| Keyword | Description | Code example |
|---|---|---|
| False, True | Data values from the data type Boolean | False == (1 > 2), True == (2 > 1) |
| and, or, not | Logical operators: • (x and y) → both x and y must be True • (x or y) → either x or y must be True • (not x) → x must be false |
x, y = True, False(x or y) == True # True(x and y) == False # True(not y) == True # True |
| break | Ends loop prematurely | while(True):break # no infinite loopprint("hello world") |
| continue | Finishes current loop iteration | while(True):continueprint("43") # dead code |
| class | Defines a new class → a real-world concept (object-oriented programming) | class Beer:def __init__(self): self.content = 1.0def drink(self): self.content = 0.0becks = Beer()becks.drink() |
| def | Defines a new function or method. First parameter (“self”) refers to the instance (implicit on calls). | (included in class example) |
| if, elif, else | Conditional execution: checks branches in order until one is True | x = int(input("your value: "))if x > 3: print("Big")elif x == 3: print("Medium")else: print("Small") |
| for, while | Loop declarations | for i in [0,1,2]: print(i)j = 0while j < 3:print(j)j = j + 1 |
| in | Checks whether element is in sequence | 42 in [2, 39, 42] # True |
| is | Checks whether both elements reference the same object | y = x = 3x is y # True[3] is [3] # False |
| None | Empty value constant | def f(): x = 2f() is None # True |
| lambda | Anonymous function | (lambda x: x + 3)(3) # returns 6 |
| return | Terminates function execution and optionally returns a value | def incrementor(x): return x + 1incrementor(4) # returns 5 |
Basic Data Types
| Type | Description | Example |
|---|---|---|
| Boolean | Truth values: True or False. Boolean operators (in order of priority): • not x • x and y • x or y Values considered False: None, 0, 0.0, '', [], {}, set() |
1. Boolean Operationsx, y = True, Falseprint(x and not y) → Trueprint(not x and y or x) → True2. Falsey conditions: if None or 0 or 0.0 or '' or [] or {} or set():print("Dead code") # Not reached |
| Integer, Float | Integers have no decimals; floats have decimal precision. Integer division // returns floor value. |
3. Arithmetic Operationsx, y = 3, 2x + y → 5x - y → 1x * y → 6x / y → 1.5x // y → 1x % y → 1-x → -3abs(-x) → 3int(3.9) → 3float(3) → 3.0x ** y → 9 |
| String | Strings are sequences of characters. Created using: 1) single quotes 'Yes' 2) double quotes "Yes" 3) triple quotes """Yes""" 4) str(...) 5) concatenation "Ma" + "hatma" |
4. Indexing and Slicings = "The youngest pope was 11 years old"s[0] → 'T's[1:3] → 'he's[-3:-1] → 'ol's[-3:] → 'old'x = s.split()x[-3] + " " + x[-1] + " " + x[2] + "s" → '11 old popes'5. String Methods: y = " This is lazy\t\n "y.strip() → 'This is lazy'"DrDre".lower() → 'drdre'"attention".upper() → 'ATTENTION'"smartphone".startswith("smart") → True"smartphone".endswith("phone") → True"another".find("other") → 2"cheat".replace("ch","m") → 'meat'','.join(["F","B","I"]) → 'F,B,I'len("Rumpelstiltskin") → 15"ear" in "earth" → True |
Complex data types
| Category | Description | Example |
|---|---|---|
| List | A container type storing a sequence of elements. Lists are mutable. | l = [1, 2, 2]len(l) → 3 |
| Adding elements | Add elements with: (i) append, (ii) insert, (iii) list concatenation. append is fastest. |
[1, 2, 2].append(4) → [1, 2, 2, 4][1, 2, 4].insert(2, 2) → [1, 2, 2, 4][1, 2, 2] + [4] → [1, 2, 2, 4] |
| Removal | Removing an element can be slow. | [1, 2, 2, 4].remove(1) → [2, 2, 4] |
| Reversing | Reverses the list elements. | [1, 2, 3].reverse() → [3, 2, 1] |
| Sorting | Sorts a list. Complexity is linearithmic. | [2, 4, 2].sort() → [2, 2, 4] |
| Indexing | Finds first occurrence of element; may be slow. | [2, 2, 4].index(2) → 0[2, 2, 4].index(2, 1) → 1 |
| Stack | Lists can act as stacks using append() and pop(). |
stack = [3]stack.append(42) → [3, 42]stack.pop() → 42stack.pop() → 3 |
| Set | Unordered collection of unique elements. | basket = {'apple','eggs','banana','orange'}same = set(['apple','eggs','banana','orange']) |
| Dictionary | Stores key–value pairs. | calories = {'apple':52, 'banana':89, 'choco':546} |
| Read & write elements | Access items using keys; use keys() and values() for iteration. |
calories['apple'] < calories['choco'] → Truecalories['cappu'] = 74'apple' in calories.keys() → True52 in calories.values() → True |
| Dictionary looping | Use items() to loop through key–value pairs. |
for k,v in calories.items():print(k) if v > 500 else None→ prints "chocolate" |
| Membership operator | in checks element existence. Set containment is faster than list containment. |
basket = {'apple','eggs','banana','orange'}'eggs' in basket → True'mushroom' in basket → False |
| List & Set comprehension | Concise way to build lists or sets with for and optional if. |
List comprehension:l = [('Hi ' + x) for x in ['Alice','Bob','Pete']]→ ['Hi Alice','Hi Bob','Hi Pete']l2 = [x*y for x in range(3) for y in range(3) if x>y]→ [0, 0, 2]Set comprehension: squares = {x**2 for x in [0,2,4] if x < 4} → {0, 4} |
Functions and tricks
| Function / Trick | Description | Example | Result |
|---|---|---|---|
| map(func, iter) | Applies a function to all elements of an iterable | list(map(lambda x: x[0], ['red','green','blue'])) |
['r', 'g', 'b'] |
| map(func, i1, …, ik) | Applies function to each tuple of elements from k iterables | list(map(lambda x, y: str(x) + ' ' + y + 's', [0,2,2], ['apple','orange','banana'])) |
['0 apples','2 oranges','2 bananas'] |
| string.join(iter) | Joins elements with a separator string | ' marries '.join(['Alice','Bob']) |
'Alice marries Bob' |
| filter(func, iter) | Keeps elements for which function returns True | list(filter(lambda x: True if x>17 else False, [1,15,17,18])) |
[18] |
| string.strip() | Removes leading and trailing whitespace | " \n \t 42 \t ".strip() |
42 |
| sorted(iter) | Sorts iterable in ascending order | sorted([8,3,2,42,5]) |
[2,3,5,8,42] |
| sorted(iter, key=…) | Sorts iterable using a key function | sorted([8,3,2,42,5], key=lambda x: 0 if x==42 else x) |
[42,2,3,5,8] |
| help(func) | Shows documentation for a function | help(str.upper) |
'...to uppercase...' |
| zip(i1, i2, …) | Groups i-th elements from each iterator | list(zip(['Alice','Anna'], ['Bob','Jon','Frank'])) |
[('Alice','Bob'), ('Anna','Jon')] |
| Unzip | Unzips zipped iterables | list(zip(*[('Alice','Bob'),('Anna','Jon')])) |
[('Alice','Anna'), ('Bob','Jon')] |
| enumerate(iter) | Assigns index numbers to elements | list(enumerate(['Alice','Bob','Jon'])) |
[(0,'Alice'),(1,'Bob'),(2,'Jon')] |
| **python -m http.server | Starts a simple file-sharing server on port <P> |
Run in terminal | PC files accessible in browser |
| import antigravity | Opens “xkcd” comic about Python | import antigravity |
Opens browser comic |
| import this | Shows the Zen of Python | import this |
Prints Zen of Python text |
| Swap variables | Pythonic variable swap | a, b = 'Jane','Alice'; a, b = b, a |
a='Alice', b='Jane' |
| Unpacking args | Use * for sequences and ** for dicts as function arguments |
def f(x,y,z): return x+y*zf(*[1,3,4])f(**{'z':4,'x':1,'y':3}) |
1313 |
| Extended unpacking | Assign multiple values with unpacking | a, *b = [1,2,3,4,5] |
a=1, b=[2,3,4,5] |
| Merge dictionaries | Combine dictionaries with unpacking | x={'Alice':18}y={'Bob':27,'Ann':22}z={**x,**y} |
{'Alice':18,'Bob':27,'Ann':22} |
NumPy
| Name / Operation | Description | Example | Output |
|---|---|---|---|
| a.shape | Returns a tuple describing the dimensions of array a. |
a = np.array([[1,2],[1,1],[0,0]])print(np.shape(a)) |
(3, 2) |
| a.ndim | Number of array dimensions (length of shape tuple). | print(np.ndim(a)) |
2 |
| * (Hadamard product) | Element-wise multiplication of two arrays with the same shape. | a = np.array([[2,0],[0,2]])b = np.array([[1,1],[1,1]])print(a*b) |
[[2 0] [0 2]] |
| np.matmul(a, b), a @ b | Matrix multiplication (dot product). | print(np.matmul(a,b)) |
[[2 2] [2 2]] |
| np.arange(start, stop, step) | Creates a 1D array with evenly spaced values. | np.arange(0,10,2) |
[0 2 4 6 8] |
| np.linspace(start, stop, num) | Creates a 1D array with num evenly spaced values between start and stop. |
np.linspace(0,10,3) |
[ 0. 5. 10.] |
| np.average(a) | Computes average of all elements. | a = np.array([[2,0],[0,2]])np.average(a) |
1.0 |
| slice assignment | Replace part of an array by assigning to a slice. | a = np.array([0,1,0,0,0])a[::2] = 2 |
[2 1 2 0 2] |
| np.var(a) | Variance of values in array. | a = np.array([2,6])np.var(a) |
4.0 |
| np.std(a) | Standard deviation of values in array. | np.std(a) |
2.0 |
| np.diff(a) | Differences between consecutive elements. | fibs = np.array([0,1,1,2,3,5])np.diff(fibs, n=1) |
[1 0 1 1 2] |
| np.cumsum(a) | Cumulative sum of array elements. | np.cumsum(np.arange(5)) |
[0 1 3 6 10] |
| np.sort(a) | Returns a sorted copy of the array. | a = np.array([10,3,7,1,0])np.sort(a) |
[0 1 3 7 10] |
| np.argsort(a) | Returns indices that would sort the array. | np.argsort(a) |
[4 3 1 2 0] |
| np.max(a) | Maximum value in array. | np.max(a) |
10 |
| np.argmax(a) | Index of the maximum value. | np.argmax(a) |
0 |
| np.nonzero(a) | Indices of non-zero elements. | np.nonzero(a) |
[0 1 2 3] (for example) |
numpy/sympy
Oprettelse av numpy-matriser
Opprettelse av numerisk funksjon f = np.sin(x*y)
Integrasjon og derivasjon scipy
Integrasjon og derivasjon med sympy
Innsetting av verdier
Plotting med matplotlib
Det er en bug in matplotlib – alle lerretene er lenket sammen. To funksjoner cla() og cls() er en workaround. Noen eksempler er skjult bak kommentartegnet for å gjøre denne fanen lettere.
Plot av en graf til \(f(x)\)
Viser et 2D-array med skalardata som et bilde ved bruk av det spesifiserte «hot»-fargekartet. (Kopier til ditt vindu og ta bort kommentar-tegnet.)
Plot av en overflate i 3D. (Kopier til ditt vindu og ta bort kommentar-tegnet.)
Optimering
Unconstrained Minimization (2 Variables)
This example minimizes the two-variable function \(f(x,y)=(x-1)^{2}+(y-2.5)^{2}\), which has a minimum at \((x,y)=(1,2.5)\).
Constrained Optimization
This example demonstrates how to minimize the Rosenbrock function subject to a set of linear constraints. We aim to minimize the function \(f(x_{0},x_{1})=100(x_{1}-x_{0}^{2})^{2}+(1-x_{0})^{2}\), subject to the following constraints: \(x_{0}+2x_{1}\le 1\), \(2x_{0}+x_{1}=1\), \(0\le x_{0}\le 1\), \(-0.5\le x_{1}\le 2.0\).
Minimizing \(f(x)\) with a spherical constraint
This example minimizes the objective function \(f(x)=(x_{0}+x_{1})^{2}\) subject to the nonlinear equality constraint \(x_{0}^{2}+x_{1}^{2}=1\) (which defines a unit circle).
Linear least squares
We solve a linear least-squares problem with bounds on the variables. The goal is to minimize \(0.5*||Ax-b||^{2}\) subject to \(lb\le x\le ub\)
Linear programming
Problem: Minimize: \(f(x_{0},x_{1})=2x_{0}+3x_{1}\) Subject to: \(-x_{0}-x_{1}\le -4\), \(2x_{0}+x_{1}\le 6\), \(x_{0}\ge 0,x_{1}\ge 0\) (default bounds)