Sei sulla pagina 1di 6

11.1.2 Data Types 11.1.

2 Tipurile de date
Python provides many built-in data types. We Python ofera multe tipuri de date incorporate. Noi
describe three of the most useful descriem trei din cele mai folosite tipuri de date:
data types here: lists, strings, and dictionaries. listele, siruri de caractere, si dictionarele.
Lists. Python provides a list datatype similar to Listele. Python ofera o lista de date similara cu
lists in Scheme, except instead listele din Scheme, cu exceptia locului de
of building lists from simpler parts (that is, construire a listelor din partile mai simple (care
using cons pairs in Scheme), the este, utilizarea cons perechi in scheme), tipul listei
Python list type is a built-in datatype. The other Pyton este tipul de date incorporat. O alta
important difference is that diferenta importanta is ca listele Phyton sunt
Python lists are mutable like mlist from Section mutabile ca lista de la Sectie.
9.3. 9.3.
Lists are denoted in Python using square Listele sunt notate in Python utilizand paranteze
brackets. For example, [] denotes an patrate. De exemplu, [] noteaza o lista goala, dar
empty list and [1, 2] denotes a list containing [1,2] noteaza o lista care contine doua elemnte.
two elements. The elements in a Elementele dintr-o lista pot fi de orice tip
list can be of any type (including other lists). (incluzand o alta lista). Elementele pot fi selectate
Elements can be selected from a list using the dintr-o lista utilizand lista expresie inscrisa:
list subscript expression: ExpreisaPrimara::ExpresieInscrisa
PrimaryExpression :: SubscriptExpression ExpresieInscrisa::ExpresiePrimara[Expresie]
SubscriptExpression :: PrimaryExpression [ O expresie inscrisa evalueaza la elementul
Expression ] indexat de valoarea expreisei interioare din
A subscript expression evaluates to the element lista. De exemplu,
indexed by value of the inner a = [1, 2, 3]
expression from the list. For example, a[0] 1
a = [1, 2, 3] a[1+1] 3
a[0] 1 a[3] EroareDeIndex: lista indice in afara
a[1+1] 3 domeniului
a[3] IndexError: list index out of range Expresia p[0] in Python este analogica cu (car p) in
The expression p[0] in Python is analogous to Scheme.
(car p) in Scheme. Expreisa inscrisa are timp constant de executare;
The subscript expression has constant running spre deosebire de listele Scheme de indexare,
time; unlike indexing Scheme timpul necesarnu depinde de lungimea listei, nici
lists, the time required does not depend on the de selectia indexarii la sfarsitul listei. Motivul
length of the list even if the selection pentru aceasta este ca Python stocheaza listele
index is the end of the list. The reason for this is diferit fata de modul in care Scheme stocheaza
that Python stores lists lanturi de perechi. Elementele unei liste Python
internally differently from how Scheme stores sunt stocate ca un bloc de memorie , deci locatia
as chains of pairs. The elements elementului k poate fi calculata direct prin
of a Python list are stored as a block in adaugarea de k ori marimea unui element din lista.
memory, so the location of the k O expresie inscrisa de asemenea poate selecta
th element sirul de elemente dintr-o lista:
can be calculated directly by adding k times the ExpresieInscrisa::ExpresiePrimara
size of one element to the [ObligatieScazuta:ObligatieRidicata]
location of the start of the list. Obligatie :: Expreisa | e
A subscript expression can also select a range Expresiile inscrise cu siruri evaluate in o lista
of elements from the list: cotin elemente intre obligatia scazuta si
SubscriptExpression :: PrimaryExpression [ obligatia ridicata. Daca obligata scazuta lipseste,
BoundLow : BoundHigh ] obligatia scazuta este inceputul listei. Daca
Bound :: Expression | e obligatia ridicata lipseste, obligatia ridicata este
Subscript expressions with ranges evaluate to a sfarsitul listei. De exemplu,
list containing the elements between a=[1,2,3]
the low bound and the high bound. If the low a[:1] [1]
bound is missing, the low a[1:] [2, 3]
bound is the beginning of the list. If the high a[42:3] [3]
bound is missing, the high bound a[:] [1, 2, 3]
is the end of the list. For example, Expreisa p[1:] in Python este analogic cu (cdr p) in
a = [1, 2, 3] Scheme.
a[:1] [1] Listele Python sunt mutabile(voloare listei poate fi
a[1:] [2, 3] schimbata dupa ce a fost creata). Noi putem utiliza
a[42:3] [3] listele inscrise ca tinte pentru o expreie de
a[:] [1, 2, 3] atribuire:
The expression p[1:] in Python is analogous to Tinta :: ExrpesieInscrisa
(cdr p) in Scheme. Atribuirile ce utilizeaza sirurile ca tinte pot
Python lists are mutable (the value of a list can aduga elemente in lista precum si schimba
change after it is created). We valoarea elementelor existente:
can use list subscripts as the targets for an a = [1, 2, 3]
assignment expression: a[0] = 7
Target :: SubscriptExpression a [7, 2, 3]
Assignments using ranges as targets can add a[1:4] = [4, 5, 6]
elements to the list as well as changing a [7, 4, 5, 6]
the values of existing elements: a[1:] = [6]
a = [1, 2, 3] a [7, 6]
a[0] = 7 In tokenizarea procedurii, noi utilizam
a [7, 2, 3] tokens(jetoane)=[] pentru initializarea jetoanelor
a[1:4] = [4, 5, 6] intr-o lista goala, mai utilizam
a [7, 4, 5, 6] adaugarea,jetoanelor(actual) pentru a adauga un
a[1:] = [6] element in lista jetoanelor. Adaugarea procedurii
a [7, 6] in Python, este similara cu procedrii adaugare-
In the tokenize procedure, we use tokens = [] to mlist!(cu excepria cazului cand lucreaza pe lista
initialize tokens to an empty list, goala unde nu exista nici o modalite de a modifica
and use tokens.append(current) to append an lista de intrare nula in Scheme).
element to the tokens list. The Siruri de caractere. Alt tip de date utilizat in
Python append procedure is similar to the tokenizare tipul de datesiruri de caractere,
mlist-append! procedure (except it numit str in Python. Ca in Scheme sirurile de
works on the empty list, where there is no way caractere sunt o secventa de caractere. Spre
in Scheme to modify the null deosebire de Scheme, sirurile de caracte care sunt
input list). mutabile, tipurile de date str sunt imuabile in
Strings. The other datatype used in tokenize is Python. Ca si in Scheme, un sir de caractere este o
the string datatype, named str segventa de caractere. Spre deosebire de Scheme,
in Python. As in Scheme, a String is a sequence sirurile de caractere care sunt mutabile, tipurile de
of characters. Unlike Scheme strings which are date str sunt imuabile in Python.
mutable, the Python str datatype is immutable. Odata ce sirul de caractere a fost creat noi nu mai
Once a string putem sa-i schimbam valoarea. Asta inseamna ca
is created its value cannot change. This means toate metodele sirurilor de caractere care ar parea
all the string methods that seem ca schimba valoarea sirului de caractere defapt
to change the string values actually return new returneaza siruri noi (de exemplu,
strings (for example, capitalize() valorifica()returneaza o copie a sirului de caractere
returns a copy of the string with its first letter cu primul caracter valorificat).
capitalized). Sirul poate fi inclus in o singura citata(eg. Salut),
Strings can be enclosed in single quotes (e.g., citate duble(eg,salut),si citate duble
'hello'), double quotes (e.g., ''hello''), triple(eg,salut un sir in citatele duble
and triple-double quotes (e.g., '' '' ''hello'' '' ''; a triple poate deschide linii multiple). In programul
string inside triple quotes can span nostru exemplu, noi utilizam expresia atribuire,
multiple lines). In our example program, we use curent= (doua citate singure), pentru a initializa
the assignment expression, valoarea curentului la sirul gol. Intrarea, s, este un
current = ' ' (two single quotes), to initialize the obiect sir. Adaugarea operatorului poate fi utilizata
value of current to the empty pentru concatenarea a doua siruri de caractere. In
string. The input, s, is a string object. tokenizare, noi utilizam curent=curent +c pentru a
The addition operator can be used to actualiza valoarea curentului pentru a include un
concatenate two strings. In tokenize, we caracter nou.
use current = current + c to update the value of De cand sirurile sunt imuabile nu exista o metoda
current to include a new character. de sir analogica metodei de adaugare a listei. In
Since strings are immutable there is no string schimb, adaugarea unui caracter in sir implica
method analogous to the list crearea unui obiect sir nou.
append method. Instead, appending a Dictionarele. Un dictionar este o lista de cautare
character to a string involves creating a unde valorile sunt associate cu chei. Cheile pot fi
new string object. de orice tip imuabil(sirurile si numerele in mod
Dictionaries. A dictionary is a lookup-table obisnuit sunt utilizate ca chei); valorile pot fi de
where values are associated with orice tip. Nu folosim dictionarul de tip tokenizare,
keys. The keys can be any immutable type dar este foarte util pentru implementarea cadrelor
(strings and numbers are commonly in evaluator. Un dictionar este notat folosind {}.
used as keys); the values can be of any type. Noi adaugam valoarea cheie la dictionar utilizand o
We did not use the dictionary type atribuire unde partea stanga este o expresie
in tokenize, but it is very useful for inscrisa care specifica cheia si in partea dreapta
implementing frames in the evaluator. este valoarea atribuita pentru acea cheie. De
A dictionary is denoted using curly brackets. exemplu,
The empty dictionary is {}. We Anulnasterii = {}
add a key-value pair to the dictionary using an Anulnasterii ['Euclid'] = '300BC'
assignment where the left side Anulnasterii ['Ada'] = 1815
is a subscript expression that specifies the key Anulnasterii ['Alan Turing'] = 1912
and the right side is the value Anulnasterii ['Alan Kay'] = 1940
assigned to that key. For example, Defineste anul nasterii ca un dictionare ce contine
birthyear = {} patru intrari. Cheile sunt siruri;valorile sunt
birthyear['Euclid'] = '300BC' numere,cu exceptia intrarii lui Elucid, care este sir.
birthyear['Ada'] = 1815 Noi putem obtine valoare asociata cu o cheie in
birthyear['Alan Turing'] = 1912 dictionar utilizand in expresie inscrisa. De exemplu,
birthyear['Alan Kay'] = 1940 anul nasterii[Alan Turing] evalueaza in 1912. Noi
defines birthyear as a dictionary containing four putem inlocui valoarea asociata cu o cheie
entries. The keys are all strings; utilizand aceeasi sintaxa ca adaugare a perechii
the values are numbers, except for Euclids valori cheie la dictionar. Expresia
entry which is a string. anulnasterii['Euclid'] = 300 inlocueste valoarea
We can obtain the value associated with a key anului nasterii [Elucid]cu numarul -300.
in the dictionary using a subscript Tipul dictionarului de acemenea contine o cheie cu
expression. For example, birthyear['Alan o metodacare are o intrare si o produce un
Turing'] evaluates to 1912. We can Boolean care indica daca obiectul dictionar contine
replace the value associated with a key using valoarea de intrare ca cheie. Pentru dictionarul
the same syntax as adding a keyvalue anul nasterii,
pair to the dictionary. The statement, anul nasterii.are cheie(John Backus) Fals
birthyear['Euclid'] = 300 anul nasterii.are cheie ('Ada') Adevarat
replaces the value of birthyear['Euclid'] with Tipul dictionarului de cautare si actualizarea
the number 300. operatiilor au aproximativ executare constanta:
The dictionary type also provides a method has timpul necesarpentru cautarea valorii asociative
key that takes one input and unei chei nu este scalata, deoarece marimea
produces a Boolean indicating if the dictionary dictionarului creste. Aceasta se face prin calcularea
object contains the input value unui numar pe baza cheii care determina unde va
as a key. For the birthyear dictionary, fi stocata valoarea asociata(daca aceasta cheie
birthyear.has key('John Backus') False este in dictionar). Numarul este utilizat pentru
birthyear.has key('Ada') True indexarea in o lista Python(deci are un timp
The dictionary type lookup and update constant pentru recuperarea oricarui element).
operations have approximately constant Maparea tastelor la numerele
running time: the time it takes to lookup the corespunzatoarepentru a evita cartografierea mui
value associated with a key does not scale as multor chei la aceeasi locatie este o problema
the size of the dictionary increases. This is done dificila, dar un dictionar Python se descurca bine
by computing a number pentru majoritatea seturilor de chei.
based on the key that determines where the
associated value would be stored (if
that key is in the dictionary). The number is
used to index into a structure similar
to a Python list (so it has constant time to
retrieve any element). Mapping keys
to appropriate numbers to avoid many keys
mapping to the same location in
the list is a difficult problem, but one the
Python dictionary object does well for
most sets of keys.

Potrebbero piacerti anche