2018-09-18 - Rappels sur le langage python

Links: notebook, html, PDF, python, slides, GitHub

Notebooks écrit durant la séance du 18 septembre 2018 à propos du langage Python.

a = 4
a
4
print(a)
4
b = 5
c = a + b
c
9
entier = 1
reel = 4.5
chaine = "45"
chaine = '45'
chaine = """
fgfgqlibufliszqb
"""
chaine
'nfgfgqlibufliszqbn'
print(chaine)
fgfgqlibufliszqb
couple = (4, 5)
couple
(4, 5)
nuplet = (4, 6, 7, 'e')
nuplet
(4, 6, 7, 'e')
liste = [4, 6, 7, 'e']
liste
[4, 6, 7, 'e']
nuplet[1]
6
liste[1]
6
nuplet[1] = 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-5af74e621b46> in <module>()
----> 1 nuplet[1] = 5

TypeError: 'tuple' object does not support item assignment
liste[1] = 5
liste
[4, 5, 7, 'e']
dico = {'e': 4}
dico
{'e': 4}
dico['e']
4
dico[0]  ##
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-22-08669366fa89> in <module>()
----> 1 dico[0]

KeyError: 0
dico[0] = 5
dico
{'e': 4, 0: 5}
dico['lirbfvvbfsjq'] = 'lfvlkjqslkjdf'
dico
{'e': 4, 0: 5, 'lirbfvvbfsjq': 'lfvlkjqslkjdf'}
dico[(4,5)] = 5
dico
{'e': 4, 0: 5, 'lirbfvvbfsjq': 'lfvlkjqslkjdf', (4, 5): 5}
dico[ [4,6] ] = 6
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-3097bf2b8dc7> in <module>()
----> 1 dico[ [4,6] ] = 6

TypeError: unhashable type: 'list'
texte = "llmmaab"
dico = {}
for c in texte:
    if c in dico:
        print('+1')
        dico[c] = dico[c] + 1
    elif c == 'l':
        print('+2')
        dico[c] = 0.5
    else:
        print('+3')
        dico[c] = 1
    print(c, dico)
dico
+2
l {'l': 0.5}
+1
l {'l': 1.5}
+3
m {'l': 1.5, 'm': 1}
+1
m {'l': 1.5, 'm': 2}
+3
a {'l': 1.5, 'm': 2, 'a': 1}
+1
a {'l': 1.5, 'm': 2, 'a': 2}
+3
b {'l': 1.5, 'm': 2, 'a': 2, 'b': 1}
{'l': 1.5, 'm': 2, 'a': 2, 'b': 1}
def fonction_histogramme(texte):
    dico = {}
    for c in texte:
        if c in dico:
            dico[c] = dico[c] + 1
        elif c == 'l':
            dico[c] = 0.5
        else:
            dico[c] = 1
    return dico

fonction_histogramme('eriuhgier')
{'e': 2, 'r': 2, 'i': 2, 'u': 1, 'h': 1, 'g': 1}
dico = fonction_histogramme('eriuhgier')
print(dico['e'])
2