In [ ]:
0 1 1 2 3 5 8
0 1 1 2 3 5 813 21 34 55 89 144 233 377 610 987 1597

In [1]:
s = "ciao mamma"

In [2]:
s[0]


Out[2]:
'c'

In [3]:
s[1]


Out[3]:
'i'

In [4]:
s[-1]


Out[4]:
'a'

In [5]:
l = [1,2,3,4,5]

In [6]:
l[0]


Out[6]:
1

In [7]:
s[0:4]


Out[7]:
'ciao'

In [8]:
l[0:4]


Out[8]:
[1, 2, 3, 4]

In [9]:
s[0:-1]


Out[9]:
'ciao mamm'

In [ ]:
fib_from_string
    0 1 1 2 3 5 8
fib_from_list
    0 1 1 2 3 5 813 21 34 55 89 144 233 377 610 987 1597
fib_algo

fib = fib_from_string

In [10]:
# This is hello_who.py                # <-- i commenti iniziano con `#`
                                      #     possono essere all'inizio o a fine riga
def hello(who):                       # <-- la funzione di definisce con `def`
    print("Hello {}!".format(who))    # <-- la stampa con `print` e le stringhe con `format`

if __name__ == "__main__":            # <-- [verifica di esecuzione e non di import](https://docs.python.org/2/library/__main__.html)
    hello("mamma")                    # <-- invoco la funzione con il valore


Hello mamma!

fib(3) == 2


In [13]:
s = "0112358"
s[3]


Out[13]:
'2'

In [14]:
s[3] == 2


Out[14]:
False

In [15]:
'2' == 2


Out[15]:
False

In [17]:
type('2')


Out[17]:
str

In [18]:
type(1)


Out[18]:
int

In [19]:
int('2')


Out[19]:
2

In [20]:
type(int(2))


Out[20]:
int

In [21]:
int(s[3]) == 2


Out[21]:
True

In [24]:
def fib_from_string(i):
    s = "0112358"
    return int(s[i])
fib = fib_from_string

In [26]:
fib(3) == 2


Out[26]:
True

In [27]:
fib(2) == 1


Out[27]:
True

In [28]:
fib(1)


Out[28]:
1

In [29]:
fib(0)


Out[29]:
0

In [30]:
fib(-1)


Out[30]:
8

In [56]:
def fib_from_string(i):
    s = "0112358"
    if i < 0:
        raise ValueError(
            "indice negativo ({}) non funziona".format(i))
        
    try:
        return int(s[i])
    except IndexError:
        raise NotImplementedError(
            "Non sono stato capace da 7 in su")

fib = fib_from_string

In [62]:
int("1")


Out[62]:
1

In [73]:
s = "0112358"

In [74]:
s


Out[74]:
'0112358'

In [76]:
s["a"]


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-76-78565cebb19a> in <module>()
----> 1 s["a"]

TypeError: string indices must be integers, not str

In [49]:
s[7]


Out[49]:
'1'

In [63]:
def fib_from_string(i):
    if i < 0:
        raise ValueError(
            "indice negativo ({}) non funziona".format(i))
    elif i > 6:
        raise NotImplementedError(
            "Non sono stato capace da 7 in su")
    else:
        s = "0112358"
        return int(s[i])
    
fib = fib_from_string

In [70]:
"1" > 6


Out[70]:
True

In [65]:
fib(6)


Out[65]:
8

In [66]:
fib(7)


---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-66-9309c48a195a> in <module>()
----> 1 fib(7)

<ipython-input-63-44cc4b00b696> in fib_from_string(i)
      5     elif i > 6:
      6         raise NotImplementedError(
----> 7             "Non sono stato capace da 7 in su")
      8     else:
      9         s = "0112358"

NotImplementedError: Non sono stato capace da 7 in su

In [67]:
fib(-1)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-67-b876e14fb318> in <module>()
----> 1 fib(-1)

<ipython-input-63-44cc4b00b696> in fib_from_string(i)
      2     if i < 0:
      3         raise ValueError(
----> 4             "indice negativo ({}) non funziona".format(i))
      5     elif i > 6:
      6         raise NotImplementedError(

ValueError: indice negativo (-1) non funziona

In [68]:
fib("a")


---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-68-d0d671fc534f> in <module>()
----> 1 fib("a")

<ipython-input-63-44cc4b00b696> in fib_from_string(i)
      5     elif i > 6:
      6         raise NotImplementedError(
----> 7             "Non sono stato capace da 7 in su")
      8     else:
      9         s = "0112358"

NotImplementedError: Non sono stato capace da 7 in su

In [69]:
fib("1")


---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-69-a283560a7359> in <module>()
----> 1 fib("1")

<ipython-input-63-44cc4b00b696> in fib_from_string(i)
      5     elif i > 6:
      6         raise NotImplementedError(
----> 7             "Non sono stato capace da 7 in su")
      8     else:
      9         s = "0112358"

NotImplementedError: Non sono stato capace da 7 in su

In [77]:
int(s["a"])


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-77-f75da39041db> in <module>()
----> 1 int(s["a"])

TypeError: string indices must be integers, not str

In [78]:
s["a"]


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-78-78565cebb19a> in <module>()
----> 1 s["a"]

TypeError: string indices must be integers, not str

In [79]:
l = [0,1,1,2,3,5,8,13,21,34,55,89,144]
l[3] == 2


Out[79]:
True

In [87]:
l = [0,1,1,2,3,5,8,13,21,34,55,89,144]
def fib_from_list(i):
    if i < 0:
        raise ValueError(
            "indice negativo ({}) non funziona".format(i))
        
    return l[i]

fib = fib_from_list

In [88]:
fib(3)


Out[88]:
2

In [89]:
fib(0)


Out[89]:
0

In [90]:
fib(-1)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-90-b876e14fb318> in <module>()
----> 1 fib(-1)

<ipython-input-87-3eb5fb8f046c> in fib_from_list(i)
      3     if i < 0:
      4         raise ValueError(
----> 5             "indice negativo ({}) non funziona".format(i))
      6     return l[i]
      7 

ValueError: indice negativo (-1) non funziona

In [91]:
fib("a")


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-91-d0d671fc534f> in <module>()
----> 1 fib("a")

<ipython-input-87-3eb5fb8f046c> in fib_from_list(i)
      4         raise ValueError(
      5             "indice negativo ({}) non funziona".format(i))
----> 6     return l[i]
      7 
      8 fib = fib_from_list

TypeError: list indices must be integers, not str

In [93]:
def _fib_algo(i):
    if i == 0 or i == 1:  # operatori booleani: and or not 
        #esempi if di base https://docs.python.org/2.7/tutorial/controlflow.html
        return i
    else:
        return _fib_algo(i-1) + _fib_algo(i-2)


def fib_algo(i):
    if i < 0:
        raise ValueError(
            "indice negativo ({}) non funziona".format(i))
    return _fib_algo(i)

    
fib = fib_algo

In [67]:
def fib_algo_lb(i):
    fib_serie = [0,1]
    print("range = {}".format(xrange(1,i)))
    for _ in xrange(1, i):
        fib_serie.append(
            fib_serie[-1] + fib_serie[-2])
        print(fib_serie)
        
    return int(fib_serie[i])

In [68]:
fib_algo_lb(0)


range = xrange(1, 1)
Out[68]:
0

In [58]:
fib_serie = [0, 1, 1, 2, 3, 5]
fib_serie[-1]


Out[58]:
5

In [52]:
def fib_algo_so(i):
    numero_corrente = indice_corrente = 0
    base = 1
    
    while indice_corrente < i:
        old_base = numero_corrente
        numero_corrente += base
        base = old_base
        indice_corrente += 1
    
    return numero_corrente

fib = fib_algo_so

In [134]:
fib(8)


Out[134]:
21

In [110]:
i += 1
i


Out[110]:
5

In [111]:
i*=2
i


Out[111]:
10

In [112]:
i/=2
i


Out[112]:
5

In [113]:
i /= 2
i


Out[113]:
2

In [115]:
float(5) / 2


Out[115]:
2.5

In [117]:
5.0 % 2


Out[117]:
1.0

In [7]:
x = 0
while x < 5:
    print("ed ecco {}".format(x))
    x += 2


ed ecco 0
ed ecco 2
ed ecco 4

In [10]:
fibo_serie = [0,1,1,2,3,5,8,13,21,34,55,89,144]
for x in fibo_serie:
    print(x)


0
1
1
2
3
5
8
13
21
34
55
89
144

In [11]:
range(10)


Out[11]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [12]:
range(5,10)


Out[12]:
[5, 6, 7, 8, 9]

In [15]:
range(5,50,5)


Out[15]:
[5, 10, 15, 20, 25, 30, 35, 40, 45]

In [17]:
for i in range(11):
    print("indice {}".format(i))


indice 0
indice 1
indice 2
indice 3
indice 4
indice 5
indice 6
indice 7
indice 8
indice 9
indice 10

In [18]:
i = 0
for x in fibo_serie:
    print("fibo({}) = {}".format(i,x))
    i += 1


fibo(0) = 0
fibo(1) = 1
fibo(2) = 1
fibo(3) = 2
fibo(4) = 3
fibo(5) = 5
fibo(6) = 8
fibo(7) = 13
fibo(8) = 21
fibo(9) = 34
fibo(10) = 55
fibo(11) = 89
fibo(12) = 144

In [41]:
for i, x in enumerate(fibo_serie):
    print("fibo({}) = {}".format(i,x))


fibo(0) = 0
fibo(1) = 1
fibo(2) = 1
fibo(3) = 2
fibo(4) = 3
fibo(5) = 5
fibo(6) = 8
fibo(7) = 13
fibo(8) = 21
fibo(9) = 34
fibo(10) = 55
fibo(11) = 89
fibo(12) = 144

In [21]:
enumerate(fibo_serie)


Out[21]:
<enumerate at 0x3af5bd0>

In [22]:
list(enumerate(fibo_serie))


Out[22]:
[(0, 0),
 (1, 1),
 (2, 1),
 (3, 2),
 (4, 3),
 (5, 5),
 (6, 8),
 (7, 13),
 (8, 21),
 (9, 34),
 (10, 55),
 (11, 89),
 (12, 144)]

In [24]:
i, x = 10, 55

In [25]:
i


Out[25]:
10

In [26]:
x


Out[26]:
55

In [28]:
(10, 55) == 10,55


Out[28]:
(False, 55)

In [29]:
i, x, y = 1,2,3

In [30]:
y


Out[30]:
3

In [31]:
c = x,y

In [32]:
c


Out[32]:
(2, 3)

In [34]:
c += (10,)

In [35]:
c


Out[35]:
(2, 3, 10)

In [36]:
c += (10)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-36-6220ea5f9bc7> in <module>()
----> 1 c += (10)

TypeError: can only concatenate tuple (not "int") to tuple

In [37]:
c += 10,

In [38]:
c


Out[38]:
(2, 3, 10, 10)

In [42]:
len(fibo_serie)


Out[42]:
13

In [43]:
len(c)


Out[43]:
4

In [44]:
len(10)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-cf926263823b> in <module>()
----> 1 len(10)

TypeError: object of type 'int' has no len()

In [45]:
len("aaaa")


Out[45]:
4

In [47]:
fibo_serie


Out[47]:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

In [48]:
fibo_serie.append(89+144)

In [49]:
fibo_serie


Out[49]:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]

In [51]:
c.append


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-51-e597dc76f883> in <module>()
----> 1 c.append

AttributeError: 'tuple' object has no attribute 'append'

In [100]:
l2 = [1,2,3,4,100,10,2,4,15]
# l3 = [ x*2 for x in l2 ]
# l3 = [ x*2 for x in l2 if x > 10 ]
l3 = [ x*2 for i,x in enumerate(l2) if not i % 2 ]

# KO: l3 = [ x*2 for x in l2 if not l2.index(x) % 2 ]

# altro esempio l3 = tuple(x*2 for x in l2 )
l3


Out[100]:
[2, 6, 200, 4, 30]

In [99]:
l2 = [1,2,3,4,100,10,2,4,15]
for i, x in enumerate(l2):
    if not i % 2:
        print(x)


1
3
100
2
15

In [71]:
l3.sort()

In [72]:
l3


Out[72]:
[2, 4, 4, 6, 8, 8, 20, 30, 200]

In [75]:
s = list(set(l3))

In [76]:
s


Out[76]:
[2, 4, 6, 8, 200, 20, 30]

In [81]:
list(set(l3))


Out[81]:
[2, 4, 6, 8, 200, 20, 30]

In [101]:
d = { 1 : "SimoneC", 2: "Elena", 3: "Gianluca"}

In [102]:
d


Out[102]:
{1: 'SimoneC', 2: 'Elena', 3: 'Gianluca'}

In [103]:
d[3]


Out[103]:
'Gianluca'

In [104]:
pianibaia= {"basso" : "Aula Sirene", "terra" : "Hall"}

In [105]:
pianibaia


Out[105]:
{'basso': 'Aula Sirene', 'terra': 'Hall'}

In [106]:
stanze_per_piano = pianibaia

In [107]:
stanze_per_piano["basso"]


Out[107]:
'Aula Sirene'

In [112]:
stanze_per_piano = {'basso': ['Aula Sirene','bagno'], 
                    'terra': 'Hall'}

In [113]:
stanze_per_piano


Out[113]:
{'basso': ['Aula Sirene', 'bagno'], 'terra': 'Hall'}

In [115]:
stanze_per_piano['basso']


Out[115]:
['Aula Sirene', 'bagno']

In [116]:
stanze_per_piano['basso'][1]


Out[116]:
'bagno'

In [127]:
d2 = { "a" : 1, "b": 2, "l" : 10}

In [135]:
import collections
d2_ord = collections.OrderedDict([
        ('a', 1), ('b', 2), ('l', 10)
    ])

In [141]:
d2["c"] = 3

In [142]:
d2


Out[142]:
{'a': 1, 'b': 2, 'c': 3, 'l': 10}

In [143]:
if "c" in d2:
    print("ciao")


ciao

In [144]:
d2.keys()


Out[144]:
['a', 'c', 'b', 'l']

In [145]:
d2.values()


Out[145]:
[1, 3, 2, 10]

In [146]:
d2.items()


Out[146]:
[('a', 1), ('c', 3), ('b', 2), ('l', 10)]

In [153]:
for k, v in d2.items():
    print("Lettera {} in posizione {}".format(k,v))


Lettera a in posizione 1
Lettera c in posizione 3
Lettera b in posizione 2
Lettera l in posizione 10

In [161]:
d2_ord.has_key("c")
10 in d2_ord.values()


Out[161]:
True

In [149]:
d2_ord


Out[149]:
OrderedDict([('a', 1), ('b', 2), ('l', 10), ('c', 3)])

In [168]:
fib_d = {0:0, 1:1}
def fib(x):
    """
    Calcola fibonacci con cache su dizionario
    """
    if x in fib_d:
        return fib_d[x]

    fib_pre = fib(x-1)
    fib_d[x-1] = fib_pre

    fib_prepre = fib(x-2)
    fib_d[x-2] = fib_prepre

    return fib_pre + fib_prepre

def fib_orig(x):
    if x in (0,1):
        return x
    return fib_orig(x-1) + fib_orig(x-2)

In [169]:
fib_orig(3)


Out[169]:
2

In [171]:
fib_orig(20)


Out[171]:
6765

In [172]:
fib_orig(30)


Out[172]:
832040

In [173]:
fib_orig(35)


Out[173]:
9227465

In [174]:
fib(35)


Out[174]:
9227465

In [175]:
fib_orig(35)


Out[175]:
9227465

In [176]:
choice = raw_input("Di quale num vuoi calcolare? ")


Di quale num vuoi calcolare? 10

In [177]:
choice


Out[177]:
'10'

In [178]:
[{"name" : "Luca", "city": "Fabriano", "salary": 1238}]


Out[178]:
[{'city': 'Fabriano', 'name': 'Luca', 'salary': 1238}]

In [ ]:
def main():
    # Step 1. Finché l'utente non smette
    # Step 2. L'utente inserisce il nome
    #         Usa raw_input("Inserisci ...") per chiedere le info all'utente
    # Step 3. L'utente inserisce la città
    # Step 4. L'utente inserisce lo stipendio
    # Step 5. Inserisci il dizionario con chiavi 
    #   'name', 'city', 'salary'
    #   nella lista PEOPLE = []
    PEOPLE.append(person_d)
    # Step 6. Stampa a video PEOPLE nel modo che ti piace
    # Step 7. Riinizia da Step 1
    # FINE
    
    # ---- BONUS ----
    # Step 8. Quando l'utente smette -> scrivi i dati in un file
    #   se vuoi Step 8.1 in formato json
    #   se vuoi Step 8.2 in formato csv
    #   se vuoi Step 8.3 in formato xml
    # Step 9. Fallo anche se l'utente preme CTRL+C o CTRL+Z