28.01.2015 Views

Tutorial Python - Starship

Tutorial Python - Starship

Tutorial Python - Starship

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

a = [66.6, 333, 333, 1, 1234.5]<br />

>>> print a.count(333), a.count(66.6), a.count(’x’)<br />

2 1 0<br />

>>> a.insert(2, -1)<br />

>>> a.append(333)<br />

>>> a<br />

[66.6, 333, -1, 333, 1, 1234.5, 333]<br />

>>> a.index(333)<br />

1<br />

>>> a.remove(333)<br />

>>> a<br />

[66.6, -1, 333, 1, 1234.5, 333]<br />

>>> a.reverse()<br />

>>> a<br />

[333, 1234.5, 1, 333, -1, 66.6]<br />

>>> a.sort()<br />

>>> a<br />

[-1, 1, 66.6, 333, 333, 1234.5]<br />

5.1.1 Folosirea listelor drept stive<br />

Obiectele de tip listă pot fi folosite foarte uşor pentru a simula comportamentul unei stive. Pentru a adăuga un<br />

element pe stivă (PUSH), puteţi folosi append(). Pentru a scoate un element din stivă (POP), folosiţi pop()<br />

fără a specifica un index. Iată un exemplu:<br />

>>> stack = [3, 4, 5]<br />

>>> stack.append(6)<br />

>>> stack.append(7)<br />

>>> stack<br />

[3, 4, 5, 6, 7]<br />

>>> stack.pop()<br />

7<br />

>>> stack<br />

[3, 4, 5, 6]<br />

>>> stack.pop()<br />

6<br />

>>> stack.pop()<br />

5<br />

>>> stack<br />

[3, 4]<br />

5.1.2 Folosirea listelor drept cozi<br />

Puteţi folosi listele foarte convenabil, pentru a implementa cozi. Spre deosebire de stive unde primul element<br />

adăugat este ultimul scos, la cozi primul element adăugat este primul scos. Pentru a adăuga un element folosiţi<br />

append(), iar pentru a extrage un element folosiţi pop(0):<br />

28 Capitolul 5. Structuri de date

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!