-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path10-tuples.tex
1223 lines (1070 loc) · 42.7 KB
/
10-tuples.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% LaTeX source for ``Python for Informatics: Exploring Information''
% Copyright (c) 2010- Charles R. Severance, All Rights Reserved
%\chapter{Tuples}
%\label{tuplechap}
\chapter{Tuplas}
\label{tuplechap}
%\section{Tuples are immutable}
\section{Tuplas são imutáveis}
%\index{tuple}
%\index{type!tuple}
%\index{sequence}
\index{tupla}
\index{tipo!tupla}
\index{sequência}
%A tuple\footnote{Fun fact: The word ``tuple'' comes from the names
%given to sequences of numbers of varying lengths: single,
%double, triple, quadruple, quituple, sextuple, septuple, etc.}
%is a sequence of values much like a list.
%The values stored in a tuple can be any type, and
%they are indexed by integers.
%The important difference is that tuples are {\bf immutable}.
%Tuples are also {\bf comparable} and {\bf hashable} so we can
%sort lists of them and use tuples as key values in Python
%dictionaries.
Uma tupla\footnote{Curiosidade: A palavra ``tupla'' vem dos nomes dados a
sequências de números de diferentes tamanhos: único, dobro, triplo, quadruplo,
quíntuplo, séxtuplo, sétuplo, etc.} é uma sequência de valores bem parecida
com uma lista. Os valores guardados em uma tupla podem ser de qualquer tipo,
e eles são indexados utilizando inteiros. A princial diferença é que tuplas
são {\bf imutáveis}. Tuplas também são {\bf comparáveis} e {\bf nunca mudam}
então nós organizamos listas delas e usamos tuplas como valores em dicionários
Python.
%\index{mutability}
%\index{hashable}
%\index{comparable}
%\index{immutability}
\index{mutabilidade}
\index{hashable}
\index{comparavel}
\index{imutabilidade}
%Syntactically, a tuple is a comma-separated list of values:
Sintaticamente, uma tupla é um lista de valores separados por vírgulas:
\beforeverb
\begin{verbatim}
>>> t = 'a', 'b', 'c', 'd', 'e'
\end{verbatim}
\afterverb
%
%Although it is not necessary, it is common to enclose tuples in
%parentheses to help us quickly identify tuples when we look at
%Python code:
Apesar disto não ser necessário, é comum fechar tuplas entre parênteses para
nos ajudar a identificar rapidamente que são tuplas quando nós olhamos para
um codigo em Python:
%\index{parentheses!tuples in}
\index{parenteses!tuplas em}
\beforeverb
\begin{verbatim}
>>> t = ('a', 'b', 'c', 'd', 'e')
\end{verbatim}
\afterverb
%
%To create a tuple with a single element, you have to include the final
%comma:
Para criar uma tupla com um único elemento, você deve incluir a virgula final:
%\index{singleton}
%\index{tuple!singleton}
\index{singleton}
\index{tupla!singleton}
\beforeverb
\begin{verbatim}
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
\end{verbatim}
\afterverb
%
%Without the comma Python treats \verb"('a')" as an expression
%with a string in parentheses that evaluates to a string:
Sem a virgula o Python irá tratar \verb"('a')" como uma expressão com uma
string entre os parênteses, assim alterando o valor para uma string:
\beforeverb
\begin{verbatim}
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
\end{verbatim}
\afterverb
%
%Another way to construct a tuple is the built-in function {\tt tuple}.
%With no argument, it creates an empty tuple:
Uma outra forma de construir uma tupla é a função construtora {\tt tuple}.
Sem nenhum argumento, irá criar uma tupla vazia:
%\index{tuple function}
%\index{function!tuple}
\index{função tuple}
\index{singleton}
\beforeverb
\begin{verbatim}
>>> t = tuple()
>>> print t
()
\end{verbatim}
\afterverb
%
%If the argument is a sequence (string, list, or tuple), the result
%of the call to {\tt tuple} is a tuple with the elements of the sequence:
Se o argumento for uma sequência (string, lista ou tupla), o resultado da
chamada da {\tt tuple} será uma tupla com os elementos em sequência:
\beforeverb
\begin{verbatim}
>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')
\end{verbatim}
\afterverb
%
%Because {\tt tuple} is the name of a constructor, you should
%avoid using it as a variable name.
Por {\tt tuple} ter o mesmo nome do construtor, você deve evitar usar como
nome de alguma variável.
%Most list operators also work on tuples. The bracket operator
%indexes an element:
A maioria dos operadores das listas também funcionam nas tuplas. Os colchetes
indexam um elemento:
%\index{bracket operator}
%\index{operator!bracket}
\index{operador colchetes}
\index{operador!colchetes}
\beforeverb
\begin{verbatim}
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'
\end{verbatim}
\afterverb
%
%And the slice operator selects a range of elements.
E o operador de fatiamento seleciona uma série de elementos.
%\index{slice operator}
%\index{operator!slice}
%\index{tuple!slice}
%\index{slice!tuple}
\index{operador slice}
\index{operador!slice}
\index{tupla!slice}
\index{slice!tupla}
\beforeverb
\begin{verbatim}
>>> print t[1:3]
('b', 'c')
\end{verbatim}
\afterverb
%
%But if you try to modify one of the elements of the tuple, you get
%an error:
Mas se você tentar modificar algum elemento da tupla, você receberá um erro:
%\index{exception!TypeError}
%\index{TypeError}
%\index{item assignment}
%\index{assignment!item}
\index{exception!TypeError}
\index{TypeError}
\index{declaração de item}
\index{declaração!item}
\beforeverb
\begin{verbatim}
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
\end{verbatim}
\afterverb
%
%You can't modify the elements of a tuple, but you can replace
%one tuple with another:
Você não pode modificar os elementos de uma tupla, mas você pode substituir
uma tupla por outra:
\beforeverb
\begin{verbatim}
>>> t = ('A',) + t[1:]
>>> print t
('A', 'b', 'c', 'd', 'e')
\end{verbatim}
\afterverb
%
%\section{Comparing tuples}
\section{Comparando tuplas}
%\index{comparison!tuple}
%\index{tuple!comparison}
%\index{sort method}
%\index{method!sort}
\index{comparação!tupla}
\index{tupla!comparação}
\index{metodo short}
\index{metodo!sort}
%The comparison operators work with tuples and other sequences.
%Python starts by comparing the first element from each
%sequence. If they are equal, it goes on to the next element,
%and so on, until it finds elements that differ. Subsequent
%elements are not considered (even if they are really big).
Os operadores de comparação funcionam com tuplas e outras sequências. O
Python começa a comparar o primeiro elemento de cada sequência. Se eles forem
iguais, irá para o próximo elemento, e assim sucessivamente, até encontrar um
elemento que é diferente. Elementos subsequentes não são considerados (mesmo
que eles sejam muito grandes).
\beforeverb
\begin{verbatim}
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
\end{verbatim}
\afterverb
%
%The {\tt sort} function works the same way. It sorts
%primarily by first element, but in the case of a tie, it sorts
%by second element, and so on.
A função {\tt sort} funciona da mesma forma. Ela ordena inicialmente pelo
primeiro elemento, mas no caso de um laço, ela ordena pelo segundo elemento,
e assim sucessivamente.
%This feature lends itself to a pattern called {\bf DSU} for
Este recurso se refere a um padrão chamado {\bf DSU} para
\begin{description}
%\item[Decorate] a sequence by building a list of tuples
%with one or more sort keys preceding the elements from the sequence,
\item[Decorate] ordena uma sequência construindo uma lista de tuplas com uma
ou mais chaves ordenadas precedendo os elementos da sequência,
%\item[Sort] the list of tuples using the Python built-in {\tt sort}, and
\item[Sort] organiza a lista de tuplas utilizando o ferramenta embutida
{\tt sort} do Python, e
%\item[Undecorate] by extracting the sorted elements of the sequence.
\item[Undecorate] desordena extraindo os elementos ordenados da sequência.
\end{description}
\label{DSU}
%\index{DSU pattern}
%\index{pattern!DSU}
%\index{decorate-sort-undecorate pattern}
%\index{pattern!decorate-sort-undecorate}
%\index{Romeo and Juliet}
\index{padrão DSU}
\index{padão!DSU}
\index{padrão decorate-sort-undecorate}
\index{padrão!decorate-sort-undecorate}
\index{Romeo e Julieta}
%For example, suppose you have a list of words and you want to
%sort them from longest to shortest:
Por exemplo, suponha que você tenha uma lista de palavras e você
quer organizá-la, da mais longa para a mais curta:
\beforeverb
\begin{verbatim}
txt = 'but soft what light in yonder window breaks'
words = txt.split()
t = list()
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = list()
for length, word in t:
res.append(word)
print res
\end{verbatim}
\afterverb
%
%The first loop builds a list of tuples, where each
%tuple is a word preceded by its length.
O primeiro laço cria uma lista de tuplas, onde cada tupla é
uma palavra precedida pelo seu tamanho.
%{\tt sort} compares the first element, length, first, and
%only considers the second element to break ties. The keyword argument
%{\tt reverse=True} tells {\tt sort} to go in decreasing order.
{\tt sort} compara o primeiro elemento, tamanho, em primeiro lugar, e
somente considera o segundo elemento para quebrar o laços. O argumento
{\tt reverse=True} informa ao {\tt sort} para ir em ordem descrescente.
%\index{keyword argument}
%\index{argument!keyword}
%\index{traversal}
\index{argumento de palavra-chave}
\index{argumento!palavra-chave}
\index{atravessar}
%The second loop traverses the list of tuples and builds a list of
%words in descending order of length. The four-character words
%are sorted in {\em reverse} alphabetical order, so ``what'' appears
%before ``soft'' in the following list.
O segundo laço atravessa a lista de tuplas e constrói uma lista de palavras
ordenados por seu tamanho. As palavras de quatro caracteres são organizadas
no {\em inverso} da ordem alfabética, então ``what'' aparece antes de ``soft''
na lista a seguir.
%The output of the program is as follows:
A saída do programa será a seguinte:
%
\beforeverb
\begin{verbatim}
['yonder', 'window', 'breaks', 'light', 'what',
'soft', 'but', 'in']
\end{verbatim}
\afterverb
%
%Of course the line loses much of its poetic impact
%when turned into a Python list and sorted in
%descending word length order.
Claramente a linha perde muito do seu poder poético quanto se torna uma lista
do Python e é ordenada pelo tamanho das palavras.
%\section{Tuple assignment}
%\label{tuple assignment}
\section{Declaração de tuplas}
\label{tuple assignment}
%\index{tuple!assignment}
%\index{assignment!tuple}
%\index{swap pattern}
%\index{pattern!swap}
\index{tupla!declaração}
\index{declaração!tupla}
\index{padrão swap}
\index{padrão!swap}
%One of the unique syntactic features of the Python language
%is the ability to have a tuple on the left
%side of an assignment statement. This allows you to assign
%more than one variable at a time when the left side is a
%sequence.
Uma das principais características sintáticas da linguagem Python é a habilidade
de ter tuplas a esquerda de uma declaração de variável. Isso te permite
declarar mais que uma variável por vez quando o lado esquerdo for uma sequência.
%In this example we have a two-element list (which is a sequence) and
%assign the first and second elements of the sequence
%to the variables {\tt x} and {\tt y} in a single statement.
Nesse exemplo nós temos duas listas (que são uma sequência) e designamos o
primeiro e o segundo elemento da sequência para as variáveis {\tt x} e
{\tt y} em uma única declaração.
\beforeverb
\begin{verbatim}
>>> m = [ 'have', 'fun' ]
>>> x, y = m
>>> x
'have'
>>> y
'fun'
>>>
\end{verbatim}
\afterverb
%
%It is not magic, Python \emph{roughly} translates the
%tuple assignment syntax
%to be the following:\footnote{Python does not translate the
%syntax literally. For example, if you try this with a dictionary,
%it will not work as might expect.}
Isto não é mágica, o Python \emph{grosseiramente} traduz a sintaxe de
declaração da tupla para ser a seguinte\footnote{O Python não traduz a sintaxe
literalmente. Por exemplo, se você tentar isso com um dicionário, não irá
functionar como o experado.}:
\beforeverb
\begin{verbatim}
>>> m = [ 'have', 'fun' ]
>>> x = m[0]
>>> y = m[1]
>>> x
'have'
>>> y
'fun'
>>>
\end{verbatim}
\afterverb
%Stylistically when we use a tuple on the left side of the assignment
%statement, we omit the parentheses, but the following is an equally
%valid syntax:
Sistematicamente quando nós usamos uma tupla no lado esquerdo da declaração,
nós omitimos os parenteses, mas a seguir temos uma sintaxe igualmente válida:
\beforeverb
\begin{verbatim}
>>> m = [ 'have', 'fun' ]
>>> (x, y) = m
>>> x
'have'
>>> y
'fun'
>>>
\end{verbatim}
\afterverb
%
%A particularly clever application of tuple assignment allows
%us to {\bf swap} the values of two variables in a single statement:
Uma aplicação particularmente inteligente de declaração de tuplas nos permite
{\bf trocar} os valores de duas variáveis em uma única declaração:
\beforeverb
\begin{verbatim}
>>> a, b = b, a
\end{verbatim}
\afterverb
%
%Both sides of this statement are tuples, but
%the left side is a tuple of variables; the right side is a tuple of
%expressions. Each value on the right side
%is assigned to its respective variable on the left side.
%All the expressions on the right side are evaluated before any
%of the assignments.
Ambos os lados dessa declaração são tuplas, mas a da esquerda é uma tupla de
variáveis; a da direita é uma tupla de expressões. Cada valor no lado esquerdo
é uma atribuição a respectiva variável no lado esquerdo. Todas as expressões
no lado direito são avaliadas antes de qualquer uma das declarações.
%The number of variables on the left and the number of
%values on the right must be the same:
O número de veriaveis do lado esquerdo e o número de valores
no lado direito devem ser iguais:
%\index{exception!ValueError}
%\index{ValueError}
\index{exception!ValueError}
\index{ValueError}
\beforeverb
\begin{verbatim}
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
\end{verbatim}
\afterverb
%
%More generally, the right side can be any kind of sequence
%(string, list, or tuple). For example, to split an email address
%into a user name and a domain, you could write:
Mas geralmente, o lado direito pode ser de qualquer tipo de sequência
(string, lista, ou tupla). Por exemplo, para dividir um email em
um nome de usuario e um dominio, você pode escrever:
\index{split method}
\index{method!split}
\index{email address}
\beforeverb
\begin{verbatim}
>>> addr = '[email protected]'
>>> uname, domain = addr.split('@')
\end{verbatim}
\afterverb
%
%The return value from {\tt split} is a list with two elements;
%the first element is assigned to {\tt uname}, the second to
%{\tt domain}.
O valor retornado de {\tt split} é uma lista com dois elementos;
o primeiro elemento é declarado para {\tt uname}, o segundo para
{\tt domain}.
\beforeverb
\begin{verbatim}
>>> print uname
monty
>>> print domain
python.org
\end{verbatim}
\afterverb
%
%\section{Dictionaries and tuples}
\section{Dicionários e tuplas}
%\index{dictionary}
%\index{items method}
%\index{method!items}
%\index{key-value pair}
\index{dicionário}
\index{metodo items}
\index{metodo!items}
\index{par chave-valor}
%Dictionaries have a method called {\tt items} that returns a list of
%tuples, where each tuple is a key-value
%pair\footnote{This behavior is slightly different in Python 3.0.}.
Dicionários tem um método chamado {\tt items} que retorna uma lista de tuplas,
onde cada tupla contem um par de chave-valor. \footnote{Esse procedimento é
um pouco diferente no Python 3.0.}.
\beforeverb
\begin{verbatim}
>>> d = {'a':10, 'b':1, 'c':22}
>>> t = d.items()
>>> print t
[('a', 10), ('c', 22), ('b', 1)]
\end{verbatim}
\afterverb
%
%As you should expect from a dictionary, the items are in no
%particular order.
Como você deve esperar de um dicionário, os itens estão sem uma ordem em
particular.
%However, since the list of tuples is a list, and tuples are comparable,
%we can now sort the list of tuples. Converting a dictionary
%to a list of tuples is a way for us to output the contents of a
%dictionary sorted by key:
Entretanto, uma vez que a lista de tuplas é uma lista, e tuplas são
comparáveis, nós agora podemos organizar a lista de tuplas. Convertento
um dicionário em uma lista de tuplas é uma forma de nós exibirmos os
conteúdos de um dicionário organizado pelas chaves:
\beforeverb
\begin{verbatim}
>>> d = {'a':10, 'b':1, 'c':22}
>>> t = d.items()
>>> t
[('a', 10), ('c', 22), ('b', 1)]
>>> t.sort()
>>> t
[('a', 10), ('b', 1), ('c', 22)]
\end{verbatim}
\afterverb
%
%The new list is sorted in ascending alphabetical order by the key value.
A nova lista é organizada em ordem alfabética pelo nome da chave.
%\section{Multiple assignment with dictionaries}
\section{Múltipla declaração com dicionários}
%\index{traverse!dictionary}
%\index{dictionary!traversal}
\index{atravessar!dicionário}
\index{dicionário!atravessar}
%Combining {\tt items}, tuple assignment, and {\tt for}, you
%can see a nice code pattern for traversing the keys and values of a dictionary
%in a single loop:
Combinando {\tt items}, declaração de tuplas, e o laço {\tt for}, você pode
ver um bom modelo de código para percorrer as chaves e valores de um
dicionário em um único laço:
\beforeverb
\begin{verbatim}
for key, val in d.items():
print val, key
\end{verbatim}
\afterverb
%
%This loop has two {\bf iteration variables} because {\tt items} returns
%a list of tuples and {\tt key, val} is a tuple assignment
%that successively iterates through each of the key-value pairs in the
%dictionary.
Esse laço tem duas {\bf variáveis de iteração} pois {\tt items} retorna uma
lista de tuplas e {\tt key, val} é declaração de uma tupla que sucessivamente
itera através de cada um dos pares de chave-valor no dicionário.
%For each iteration
%through the loop, both {\tt key} and {\tt value} are advanced to the
%next key-value pair in the dictionary (still in hash order).
Para cada iteração através do laço, ambos {\tt key} e {\tt value} são
avançados para o próximo par de chave-valor no dicionário (continua em uma
ordem embaralhada).
%The output of this loop is:
A saída desse laço será:
\beforeverb
\begin{verbatim}
10 a
22 c
1 b
\end{verbatim}
\afterverb
%
%Again, it is in hash key order (i.e., no particular order).
Novamente, está embaralhada pela chave (i.e., nenhuma ordem em particular).
%If we combine these two techniques, we can print out the contents
%of a dictionary sorted by the \emph{value} stored in each key-value
%pair.
Se nós combinarmos essas duas técnicas, nós podemos imprimir o conteúdo de
um dicionário ordenado pelo \emph{valor} armazenado em cada par de chave-valor.
%To do this, we first make a list of tuples where each tuple is
%{\tt (value, key)}. The {\tt items} method would give us a list of
%{\tt (key, value)} tuples---but this time we want to sort by value, not key.
%Once we have constructed the list with the value-key tuples, it is a simple
%matter to sort the list in reverse order and print out the new, sorted list.
Para fazer isso, primeiramente criamos uma lista de tuplas onde cada tupla é
{\tt (valor, chave)}. O método {\tt items} nós dará uma lista de tuplas
{\tt (chave, valor)} ---mas agora nós queremos organizar pelos valores, não
pelas chaves. Uma vez que tenha sido construida a lista com as tuplas de
chave-valor, será simplesmente questão de organizar a lista em ordem reversa
e exibir a nova lista organizada.
\beforeverb
\begin{verbatim}
>>> d = {'a':10, 'b':1, 'c':22}
>>> l = list()
>>> for key, val in d.items() :
... l.append( (val, key) )
...
>>> l
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> l.sort(reverse=True)
>>> l
[(22, 'c'), (10, 'a'), (1, 'b')]
>>>
\end{verbatim}
\afterverb
%
%By carefully constructing the list of tuples to have the value as the first
%element of each tuple, we can sort the list of tuples and get our dictionary
%contents sorted by value.
Esteja atento quando for construir a lista de tuplas para ter os valores como
primeiro elemento de cada tupla, assim nós podemos organizar as tuplas e pegar os
conteudos do dicionário organizado por valor.
%\section{The most common words}
\section{As palavras mais comuns}
\index{Romeo and Juliet}
%Coming back to our running example of the text from \emph{Romeo and Juliet}
%Act 2, Scene 2, we can augment our program to use this technique to
%print the ten most common words in the text as follows:
Voltando ao nosso exemplo de texto do \emph{Romeo and Juliet}
Ato 2, cena 2, nós podemos aumentar nosso programa para usar essa tecnica
para exibir as dez palavras mais comuns no texto como vocÊ pode ver a seguir:
\beforeverb
\begin{verbatim}
import string
fhand = open('romeo-full.txt')
counts = dict()
for line in fhand:
line = line.translate(None, string.punctuation)
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
# Sort the dictionary by value
lst = list()
for key, val in counts.items():
lst.append( (val, key) )
lst.sort(reverse=True)
for key, val in lst[:10] :
print key, val
\end{verbatim}
\afterverb
%
%The first part of the program which reads the file and computes
%the dictionary that maps each word to the count of words in the
%document is unchanged. But instead of simply printing out
%{\tt counts} and ending the program, we construct a list
%of {\tt (val, key)} tuples and then sort the list in reverse order.
A primeira parte do programa que lê o arquivo e computa o dicionário que
mapeia cada palavra para contar as palavras no documento está inalterado. Mas
ao invés de simplesmente exibir {\tt counts} e finalizar o programa, nós
construimos uma lista de tuplas {\tt (val, key)} e então ordenamos a
lista em ordem reversa.
%Since the value is first, it will be used for the comparisons.
%If there is more than one tuple with the same value, it will look
%at the second element (the key), so tuples where the value is the
%same will be further sorted by the alphabetical order of the key.
Uma vez que o valor seja o primeiro, ele será usado nas comparações. Se tiver
mais que uma tupla com o mesmo valor, ele irá comparar com o segundo elemento
(a chave), então em tuplas onde os valores são os mesmos ainda serão
classificadas pela ordem alfabética das chaves.
%At the end we write a nice {\tt for} loop which does a multiple
%assignment iteration and prints out the ten most common words
%by iterating through a slice of the list ({\tt lst[:10]}).
No final nós escrevemos um laço {\tt for} que faz múltiplas iterações em
declarações e exibe as dez palavras mais comuns iterando através de um
fatiamento da lista ({\tt lst[:10]}).
%So now the output finally looks like what we want for our word
%frequency analysis.
Desta forma a saída para nosso analisador de frequência de palavras finalmente
será como esperamos.
\beforeverb
\begin{verbatim}
61 i
42 and
40 romeo
34 to
34 the
32 thou
32 juliet
30 that
29 my
24 thee
\end{verbatim}
\afterverb
%
%The fact that this complex data parsing and analysis
%can be done with an easy-to-understand 19-line Python
%program is one reason why Python is a good choice as a language
%for exploring information.
O fato de que esse complexo sistema de decomposição e análise de dados pode
ser feito utilizando 19 linhas de fácil compreensão é uma das razões de o
Python ser uma boa escolha para explorar informações.
%\section{Using tuples as keys in dictionaries}
\section{Usando tuplas como chaves em dicionários}
%\index{tuple!as key in dictionary}
%\index{hashable}
\index{tupla!como chave em um dicionário}
\index{hashable}
%Because tuples are {\bf hashable} and lists are not, if we want to
%create a {\bf composite} key to use in a dictionary we must use a tuple as
%the key.
Por conta de tuplas serem {\bf imutáveis} e listas não, se nós quisermos criar
uma chave {\bf composta} para usar em um dicionário nós usamos a tupla como
chave.
%We would encounter a composite key if we wanted to create a
%telephone directory that maps
%from last-name, first-name pairs to telephone numbers. Assuming
%that we have defined the variables
%{\tt last}, {\tt first}, and {\tt number}, we could write
%a dictionary assignment statement as follows:
Nós devemos encontrar uma chave composta se nós quisermos criar uma lista
telefônica que mapeia o último nome, e o primeiro nome para os números
de telefones. Assumindo que nós definimos as variáveis {\tt last},
{\tt first}, e {\tt number}, nós podemos escrever uma declaração de um
dicionário assim:
\beforeverb
\begin{verbatim}
directory[last,first] = number
\end{verbatim}
\afterverb
%
%The expression in brackets is a tuple. We could use tuple
%assignment in a {\tt for} loop to traverse this dictionary.
A expressão entres os colchetes é uma tupla. Nós podemos usar tuplas em
declarações em um laço {\tt for} para percorrer esse dicionário.
%\index{tuple!in brackets}
\index{tupla!nos colchetes}
\beforeverb
\begin{verbatim}
for last, first in directory:
print first, last, directory[last,first]
\end{verbatim}
\afterverb
%
%This loop traverses the keys in {\tt directory}, which are tuples. It
%assigns the elements of each tuple to {\tt last} and {\tt first}, then
%prints the name and corresponding telephone number.
Esse laço percorre as chaves no {\tt directory}, que são tuplas. E atribui
os elementos de cada tupla para o {\tt last} e {\tt first}, então exibe o
nome do número de telefone correspondente.
%\section{Sequences: strings, lists, and tuples---Oh My!}
%\index{sequence}
\section{Sequências: strings, listas, e tuplas---Oh!}
\index{sequência}
%I have focused on lists of tuples, but almost all of the examples in
%this chapter also work with lists of lists, tuples of tuples, and
%tuples of lists. To avoid enumerating the possible combinations, it
%is sometimes easier to talk about sequences of sequences.
Nós estavamos focados em listas de tuplas, mas quase todos os exemplos deste
capítulo também funcionam com listas de listas, tuplas de tuplas, e tuplas de
listas. Para evitar de numerar possíveis combinações, é mais fácil falar
sobre sequências de sequências.
%In many contexts, the different kinds of sequences (strings, lists, and
%tuples) can be used interchangeably. So how and why do you choose one
%over the others?
Em varios contextos, os diferentes tipos de sequências (strings, listas e
tuplas) podem ser usadas de forma intercambiável. Então por que você
escolheria um ao invés de outro?
%\index{string}
%\index{list}
%\index{tuple}
%\index{mutability}
%\index{immutability}
\index{string}
\index{lista}
\index{tupla}
\index{mutabilidade}
\index{imutabilidade}
%To start with the obvious, strings are more limited than other
%sequences because the elements have to be characters. They are
%also immutable. If you need the ability to change the characters
%in a string (as opposed to creating a new string), you might
%want to use a list of characters instead.
Para começar com o óbvio, strings são mais limitadas que outras sequências
por conta dos elementos terem que ser caracteres. Elas também são imutáveis.
Se você necessita da habilidade de mudar os caracteres em uma string (em vez
de criar uma nova string), você deveria usar uma lista de caracteres como
alternativa.
%Lists are more common than tuples, mostly because they are mutable.
%But there are a few cases where you might prefer tuples:
Listas são mais comuns que tuplas, principalmente por serem mutáveis.
Mas tem alguns casos onde você irá preferir usar tuplas:
\begin{enumerate}
%\item In some contexts, like a {\tt return} statement, it is
%syntactically simpler to create a tuple than a list. In other
%contexts, you might prefer a list.
\item Em alguns contextos, como uma declaração {\tt return}, será
sintaticamente mais simples criar uma tupla do que uma lista. Em outros
contextos, você pode preferir usar uma lista.
%\item If you want to use a sequence as a dictionary key, you
%have to use an immutable type like a tuple or string.
\item Se você quiser usar uma sequência como uma chave de dicionário, você
deve usar uma do tipo imutável, como uma tupla ou string.
%\item If you are passing a sequence as an argument to a function,
%using tuples reduces the potential for unexpected behavior
%due to aliasing.
\item Se você estiver passando uma sequência como um argumento para uma função,
utilizar tuplas reduz o potencial de ter um comportamento inexperado devido a
descontinuidade.
\end{enumerate}
%Because tuples are immutable, they don't provide methods
%like {\tt sort} and {\tt reverse}, which modify existing lists.
%However Python provides the built-in functions {\tt sorted}
%and {\tt reversed}, which take any sequence as a parameter
%and return a new sequence with the same elements in a different
%order.
Por conta das tuplas serem imutáveis, elas não tem métodos como o {\tt sort}
e {\tt reverse}, os quais modificam a lista existente. No entando o Python
fornece as funções embutidas {\tt sorted} e {\tt reversed}, as quais pegam
qualquer sequência como um parâmetro e retornam uma nova sequência com os
mesmos elementos em uma ordem diferente.
%\index{sorted function}
%\index{function!sorted}
%\index{reversed function}
%\index{function!reversed}
\index{função sorted}
\index{função!sorted}
\index{função reversed}
\index{função!reversed}
%\section{Debugging}
\section{Debugando}
%\index{debugging}
%\index{data structure}
%\index{shape error}
%\index{error!shape}
\index{debugando}
\index{estrutura de dados}
\index{erro de forma}
\index{erro!forma}
%Lists, dictionaries and tuples are known generically as {\bf data
% structures}; in this chapter we are starting to see compound data
%structures, like lists of tuples, and dictionaries that contain tuples
%as keys and lists as values. Compound data structures are useful, but
%they are prone to what I call {\bf shape errors}; that is, errors
%caused when a data structure has the wrong type, size, or composition,
%or perhaps you write some code and forget the shape of your data
%and introduce an error.
Listas, dicionários e tuplas são geralmente conhecidos como {\bf estruturas de
dados}; neste capítulo nós estamos começando a ver estruturas de dados
compostas, como listas de tuplas, e dicionários que contem tuplas como chaves
e listas como valores. Estruturas de dados compostos são úteis, mas elas são
inclinadas a erros, os quais eu chamo de {\bf erros de forma}; que são erros
causados quando uma estrutura de dados contém o tipo errado, tamanho ou
composição, ou talvez você tenha escrito algum código e esqueceu de modelar
seus dados e introduzir um erro.
%For example, if you are expecting a list with one integer and I
%give you a plain old integer (not in a list), it won't work.
Por exemplo, se você estiver esperando uma lista com um inteiro e eu lhe der
um único inteiro (que não está em uma lista), não irá functionar.
%When you are debugging a program, and especially if you are
%working on a hard bug, there are four things to try:
Quando você estiver debugando um programa, e especialmente se você estiver
trabalhando em um bug difícil, tem algunas coisas que você deve tentar:
\begin{description}
%\item[reading:] Examine your code, read it back to yourself, and
%check that it says what you meant to say.
\item[lendo:] Examine o seu codigo, leia-o novamente para si mesmo, e
verifique se ele representa o que você queria que dizer.
%\item[running:] Experiment by making changes and running different
%versions. Often if you display the right thing at the right place
%in the program, the problem becomes obvious, but sometimes you have to
%spend some time to build scaffolding.
\item[rodando:] Experimente fazer alterações e rodar diferentes versões.
Frequentemente se você exibir a coisa certa no lugar certo no programa, o
problema se tornará óbvio, mas algumas vezes você deve gastar algum tempo
construindo uma plataforma.
%\item[ruminating:] Take some time to think! What kind of error
%is it: syntax, runtime, semantic? What information can you get from
%the error messages, or from the output of the program? What kind of
%error could cause the problem you're seeing? What did you change
%last, before the problem appeared?
\item[refletir:] Gaste um tempo pensando! Que tipo de erro é esse: sintaxe,
tempo de execução, semântico? Que informação você recebeu das mensagens de
erro, ou da saída do programa? Que tipo de erro pode causar o problema que
você está vendo? Oque você mudou por ultimo, antes do problema aparecer?
%\item[retreating:] At some point, the best thing to do is back
%off, undoing recent changes, until you get back to a program that
%works and that you understand. Then you can start rebuilding.
\item[retrocedendo:] Em alguma hora, a melhor coisa a se fazer é voltar atrás,
desfazer as mudanças recentes, até que você volte ao programa que funciona e
que você conhece. Então você pode começar a reconstruir.
\end{description}
%Beginning programmers sometimes get stuck on one of these activities
%and forget the others. Each activity comes with its own failure
%mode.
Programadores iniciantes as vezes ficam presos em uma dessas ações e esquecem
as outras. Cada ação vem com o seu próprio fracasso.
%\index{typographical error}
\index{erro tipográfico}
%For example, reading your code might help if the problem is a
%typographical error, but not if the problem is a conceptual
%misunderstanding. If you don't understand what your program does, you
%can read it 100 times and never see the error, because the error is in
%your head.
Por exemplo, ler o seu código pode ajudar a descobrir se o problema é um erro
tipográfico, mas não irá ajudar se o programa é um conceito mal entendido.
%\index{experimental debugging}
\index{debug experimental}
%Running experiments can help, especially if you run small, simple
%tests. But if you run experiments without thinking or reading your
%code, you might fall into a pattern I call ``random walk programming'',
%which is the process of making random changes until the program
%does the right thing. Needless to say, random walk programming
%can take a long time.
Rodar experimentos pode ajudar, especialmente se você rodar teste pequenos e
simples. Mas se você rodar experimentos sem pensar ou ler o seu código,
poderá cair em um padrão chamado ``programação aleatória'', que é o processo
de fazer mudanças aleatórias até o programa fazer a coisa certa.
Desnecessário dizer que programação aleatória pode consumir bastante tempo.
%\index{random walk programming}
%\index{development plan!random walk programming}
\index{programação aleatória}