Skip to content

Commit

Permalink
Functional Python: 4th version
Browse files Browse the repository at this point in the history
  • Loading branch information
tisnik committed Aug 7, 2023
1 parent 27edf04 commit 595e85a
Showing 1 changed file with 275 additions and 7 deletions.
282 changes: 275 additions & 7 deletions docs/functional_python.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,25 @@

---

### Lambdas

- anonymous functions
- not fully true in Python
- it's basically just an expression

---

### Lambdas

```python
(lambda x,y:x+y)(1, 2)

foo=lambda x,y:x+y
foo(1,2)
```

---

### Higher order functions

- must exist by definition
Expand All @@ -87,27 +106,111 @@

---

#### Higher order functions

```python
def foo():
def bar():
print("BAR")
return bar

x = foo()
x()
```

---

#### Higher order functions

```python
def add(x, y):
return x + y


def mul(x, y):
return x * y


def less_than(x, y):
return x < y


def get_operator(symbol):
operators = {
"+": add,
"*": mul,
"<": less_than,
}
return operators[symbol]


def calc(operator, x, y):
return operator(x, y)


z = calc(get_operator("+"), 10, 20)
print(z)

z = calc(get_operator("*"), 10, 20)
print(z)

z = calc(get_operator("<"), 10, 20)
print(z)
```

---

#### `map`

```python
values = range(-10, 11)

converted = map(abs, values)
print(list(converted))
```

---

#### `filter`

```python
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
words = message.split()

filtered = filter(lambda word: len(word) > 4, words)
print(list(filtered))
```

---

#### `reduce`

---
```python
from functools import reduce

### Lambdas

- anonymous functions
- not fully true in Python
- it's basically just an expression
def multiply(x, y):
return x * y


x = range(1, 11)
print(x)

y = reduce(multiply, x)
print(y)
```

---

#### Lambdas
### Factorial computation

```python
n = range(0, 11)

factorials = map(lambda n: reduce(lambda a, b: a*b, range(1, n+1), 1), n)

print(list(factorials))
```

---

Expand All @@ -124,9 +227,50 @@

#### Counter (incorrect)

```python
def createCounter():
counter = 0
def next():
counter += 1
return counter
return next

counter1 = createCounter()
counter2 = createCounter()
for i in range(1,11):
result1 = counter1()
result2 = counter2()
print("Iteration #%d" % i)
print(" Counter1: %d" % result1)
print(" Counter2: %d" % result2)
```

---

#### Counter (correct for Python 2.x)

```python
def createCounter():
counter = [0]
def next():
counter[0] += 1
return counter[0]
return next
```

---

#### Counter (correct)
#### Counter (correct for Python 3.x)

```python
def createCounter():
counter = 0
def next():
nonlocal counter
counter += 1
return counter
return next
```

---

Expand All @@ -142,18 +286,34 @@

#### Tuple comprehension

```python
```

---

#### List comprehension

```python
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
words = message.split()

lengths = [len(word) for word in words]
```

---

#### Set comprehension

```python
```

---

#### Dict comprehension

```python
```

---

### Partial functions
Expand All @@ -162,10 +322,44 @@

#### `partial` usage

```python
from functools import partial


def mul(x, y):
return x * y


print(mul(6, 7))

print()

doubler = partial(mul, 2)


for i in range(11):
print(i, doubler(i))
```

---

### `partialmethod` usage

```python
class Foo:
def __init__(self):
self._enabled = False

def set_enabled(self, state):
self._enabled = state

enable = partialmethod(set_enabled, True)
disable = partialmethod(set_enabled, False)

def __str__(self):
return "Foo that is " + ("enabled" if self._enabled else "disabled")
```

---

### Caching
Expand All @@ -178,3 +372,77 @@
---

#### `lru_cache` usage

```python
from time import time
from functools import lru_cache

@lru_cache
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)


max_n = 300

for _ in range(10):
start = time()
result = fib(max_n)
end = time()
print(result, end - start)
```

---

#### `lru_cache` usage #2

```python
from time import time
from functools import lru_cache

@lru_cache
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)


max_n = 300

for i in range(20):
if i % 5 == 0:
fib.cache_clear()
print(fib.cache_info())
start = time()
result = fib(max_n)
end = time()
print(result, end - start)
```

---

#### `cache` usage

```python
from time import time
from functools import cache

@cache
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)


max_n = 300

for i in range(20):
if i % 5 == 0:
fib.cache_clear()
print(fib.cache_info())
start = time()
result = fib(max_n)
end = time()
print(result, end - start)
```

0 comments on commit 595e85a

Please sign in to comment.