Skip to content
Snippets Groups Projects
Commit 087c039d authored by Helene Coullon's avatar Helene Coullon
Browse files

update tp python

parent 134f6446
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Map reduce
Le code disponible ci-dessous est celui du cours. Bien entendu dans ce cas on est limités par la puissance et la mémoire de la machine utilisée.
Le code disponible ci-dessous donne des exemples d'utilisation.
%% Cell type:code id: tags:
``` python
from itertools import chain
from functools import reduce
```
%% Cell type:markdown id: tags:
## Map
%% Cell type:code id: tags:
%% Cell type:markdown id: tags:
``` python
Exemples d'utilisation de Map en Python. Nous définissons aussi un `flatmap`.
Exécutez et comprenez ces codes.
# Define flat_map using map and itertools.chain
def flat_map(func, iterable):
return list(chain.from_iterable(map(func, iterable)))
%% Cell type:code id: tags:
``` python
# Initial list of words
words = ["The", "Dark", "Knight", "Rises"]
# Map to get the length of each word
lengths = list(map(len, words))
print("Lengths:", lengths)
# The List function creates a list from any iterable object
print("Test on list function:",list("Test"))
# Map to get each word as a list of characters
list_of_chars = list(map(list, words))
print("List of characters:", list_of_chars)
# The ord function returns the ASCII value of a character
print("Test on ord function:",ord("T"))
# Map to get the ASCII value of the first character of each word
# This example uses a lambda anonymous function: https://www.w3schools.com/python/python_lambda.asp
list_of_asciis = list(map(lambda word: ord(word[0]), words))
print("List of ASCII values:", list_of_asciis)
# Define flat_map using map and itertools.chain
def flat_map(func, iterable):
return list(chain.from_iterable(map(func, iterable)))
# FlatMap to flatten all characters
# compare the output to the list_of_chars = list(map(list, words))
chars = flat_map(list, words)
print("Flattened characters:", chars)
# Map to increment each word length by 1
incs = list(map(lambda length: length + 1, lengths))
print("Incremented lengths:", incs)
```
%% Output
Lengths: [3, 4, 6, 5]
Test on list function: ['T', 'e', 's', 't']
List of characters: [['T', 'h', 'e'], ['D', 'a', 'r', 'k'], ['K', 'n', 'i', 'g', 'h', 't'], ['R', 'i', 's', 'e', 's']]
Test on ord function: 84
List of ASCII values: [84, 68, 75, 82]
Flattened characters: ['T', 'h', 'e', 'D', 'a', 'r', 'k', 'K', 'n', 'i', 'g', 'h', 't', 'R', 'i', 's', 'e', 's']
Incremented lengths: [4, 5, 7, 6]
%% Cell type:markdown id: tags:
## Reduce
%% Cell type:markdown id: tags:
Exemples d'utilisation de Reduce en Python.
Exécutez et comprenez ces codes.
%% Cell type:code id: tags:
``` python
words = ["The", "Dark", "Knight", "Rises"]
lengths = list(map(len, words)) # Creates a list of lengths: [3, 4, 6, 5]
# Concatenates all elements in `words` into a single string.
res1 = reduce(lambda x, y: x + y, words) if words else None
print("res1:", res1)
# Concatenates all elements in `words`, then adds "AndFalls" at the end.
res2 = reduce(lambda x, y: x + y, words + ["AndFalls"])
print("res2:", res2)
# Concatenates "NaNa" at the beginning, then adds all elements in `words`.
res3 = reduce(lambda x, y: x + y, ["NaNa"] + words)
print("res3:", res3)
# Takes the first letter of each word in `words` and concatenates them.
res4 = reduce(lambda x, y: x + y, map(lambda word: word[0], words))
print("res4:", res4)
# Sums up all the elements in `lengths`, which represents the total length of all words.
res5 = reduce(lambda x, y: x + y, lengths)
print("res5:", res5)
```
%% Output
res1: TheDarkKnightRises
res2: TheDarkKnightRisesAndFalls
res3: NaNaTheDarkKnightRises
res4: TDKR
res5: 18
%% Cell type:markdown id: tags:
## Exercice
%% Cell type:markdown id: tags:
Ecrire un programme qui calcule la distance totale entre une série de points en 2D, connectés séquentiellement comme un trajet.
On vous donne une liste de points en 2D, chaque point étant représenté par un tuple (x, y).
Ecrire un programme qui calcule la distance Euclidienne totale entre une série de points en 2D connectés séquentiellement l'un après l'autre.
Utilisez map pour calculer la distance entre chaque paire de points consécutifs.
On vous donne une liste de points en 2D, chaque point étant représenté par un tuple (x, y).
Utilisez ensuite reduce pour calculer la distance totale du trajet reliant tous les points.
- Utilisez map pour calculer la distance entre chaque paire de points consécutifs.
- Utilisez ensuite reduce pour calculer la distance totale du trajet reliant tous les points.
```python
points = [(0, 0), (3, 4), (7, 1), (10, 10)]
```
%% Cell type:code id: tags:
``` python
from functools import reduce
import math
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment