In [1]:
l = [1, 4, 3];
In [2]:
l
Out[2]:
In [4]:
l.append(6)
In [5]:
l
Out[5]:
In [6]:
l+l
Out[6]:
In [7]:
3*l
Out[7]:
In [8]:
l
Out[8]:
In [9]:
range(10)
Out[9]:
In [11]:
range(3, 10, 2)
Out[11]:
In [15]:
def listb(n):
if n == 0:
return [[]]
rec = listb(n-1)
return [ [0]+l for l in rec ] + [ [1] + l for l in rec ]
In [16]:
listb(4)
Out[16]:
In [17]:
[len(listb(i)) for i in range(10)]
Out[17]:
In [19]:
p = Primes()
In [20]:
p
Out[20]:
In [22]:
l = [3,2,5,6]
In [23]:
it = iter(l)
In [24]:
it
Out[24]:
In [25]:
it.next()
Out[25]:
In [26]:
it.next()
Out[26]:
In [27]:
it.next()
Out[27]:
In [28]:
it.next()
Out[28]:
In [29]:
it.next()
In [30]:
def listCompo(n):
if n == 0:
return [[]]
res = []
for k in range(1, n+1):
res.extend([[k] + l for l in listCompo(n-k)])
return res
In [31]:
listCompo(0)
Out[31]:
In [32]:
listCompo(1)
Out[32]:
In [33]:
listCompo(2)
Out[33]:
In [34]:
listCompo(3)
Out[34]:
In [35]:
listCompo(4)
Out[35]:
In [36]:
[len(listCompo(i)) for i in range(11)]
Out[36]:
In [38]:
def ajoute1(l):
res = list(l) # copie l
res[0]+=1
return res
In [40]:
l = [4,3,1,2]; ajoute1(l), l
Out[40]:
In [43]:
def listC(n):
if n == 0:
return [[]]
if n == 1:
return [[1]]
rec = listC(n-1)
return [[1] + l for l in rec] + [ajoute1(l) for l in rec]
In [46]:
listC(6)
Out[46]:
Iteration et Yield en Python
In [47]:
def demoyield():
yield 1
yield "toto"
yield 7
In [48]:
it = demoyield()
In [49]:
it
Out[49]:
In [50]:
it.next()
Out[50]:
In [51]:
it.next()
Out[51]:
In [52]:
it.next()
Out[52]:
In [53]:
it.next()
In [54]:
def bla(n):
for i in range(n):
yield i
In [55]:
it = bla(5)
In [56]:
it.next()
Out[56]:
In [57]:
it.next()
Out[57]:
In [58]:
list(it)
Out[58]:
In [60]:
def genBin(n):
if n == 0:
yield []
else:
for l in genBin(n-1):
yield [0] + l
for l in genBin(n-1):
yield [1] + l
In [61]:
it = genBin(4)
In [62]:
it.next()
Out[62]:
In [63]:
it.next()
Out[63]:
In [64]:
list(it)
Out[64]:
Memoization
In [68]:
@cached_function
def binom(n, k):
if k == 0:
return 1
if k == n:
return 1
return binom(n-1, k) + binom(n-1, k-1)
In [69]:
binom(100, 50)
Out[69]:
In [ ]:
In [ ]:
In [ ]: