├── LICENSE
├── README.md
└── notebooks
├── .ipynb_checkpoints
└── 01-checkpoint.ipynb
├── KdTree.ipynb
├── LifoQueue.ipynb
├── Queue-deque.ipynb
├── SortedList.ipynb
├── dict.ipynb
├── list.ipynb
├── set.ipynb
└── tree.ipynb
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Tipos abstratos de dados com Python
2 |
3 | Este repositório foi pensado para quem já programa em Python, mas ainda não teve contato profundo com abstrações de alto nível como conjuntos e árvores.
4 |
5 | > Se você ainda não teve o primeiro contato com Python, dê uma olhada neste [repositório](https://github.com/leobezerra/python-zero) 🙃
6 |
7 | ## Índice
8 |
9 | 1. [Conjuntos](#conjuntos)
10 | 2. [Dicionários](#dicionários)
11 | 3. [Listas ordenadas manualmente](#listas-ordenadas-manualmente)
12 | 4. [Listas ordenadas automaticamente](#listas-ordenadas-automaticamente)
13 | 5. [Pilhas](#pilhas)
14 | 6. [Filas e deques](#filas-e-deques)
15 | 7. [Árvores](#árvores)
16 | 8. [Consultas espaciais](#consultas-espaciais)
17 |
18 | ---
19 |
20 | ### Conjuntos
21 |
22 | Implementações:
23 | - Python: `set`
24 | - C++: `unordered_set`, `unordered_multiset`
25 |
26 | Autores:
27 | - Anderson Pereira Torres de Sá Neto - [github/andersonptsn](https://github.com/andersonptsn)
28 | - Danilo Miranda de Medeiros Galvão - [github/Fisiquelaz](https://github.com/Fisiquelaz)
29 | - João Mendes Lopes Neto - [github/joaomendesln](https://github.com/joaomendesln)
30 | - Mateus Firmino Barros - [github/mateusfb](https://github.com/mateusfb)
31 | - Matheus Coelho Gurgel do Amaral - [github/matheuscga](https://github.com/matheuscga)
32 |
33 | Notebook:
34 |
35 | [](https://colab.research.google.com/github/leobezerra/python-tads/blob/master/notebooks/set.ipynb)
36 | [](https://mybinder.org/v2/gh/leobezerra/python-tads/master)
37 | [](https://youtu.be/24bsYVe85t8?t=620)
38 | [Voltar para o índice](#índice)
39 |
40 | ---
41 |
42 | ### Dicionários
43 |
44 | Implementações:
45 | - Python: `dict`
46 | - C++: `unordered_map`, `unordered_multimap`
47 |
48 | Autores:
49 | - João Marcos Pereira Bezerra - [github.com/marcospb19](https://github.com/marcospb19)
50 | - João Vítor Fonseca de Mendonça - [github.com/vitor177](https://github.com/vitor177)
51 | - Marcelo Ezequiel Moura Aragão - [github.com/marcelomoura1511](https://github.com/marcelomoura1511)
52 | - Marlon Secundo de Oliveira Ferreira - [github.com/marlonsecundo](https://github.com/marlonsecundo)
53 |
54 | Notebook:
55 |
56 | [](https://colab.research.google.com/github/leobezerra/python-tads/blob/master/notebooks/dict.ipynb)
57 | [](https://mybinder.org/v2/gh/leobezerra/python-tads/master)
58 | [](https://youtu.be/uUl0CF3EwoI)
59 | [Voltar para o índice](#índice)
60 |
61 | ---
62 |
63 | ### Listas ordenadas manualmente
64 |
65 | Implementações:
66 | - Python: `list`
67 | - C++: `array, vector, list, forward_list`
68 |
69 | Autores:
70 | - Acsa Laiane Arcanjo Augusto
71 | - Anna Beatriz de Souza Albuquerque
72 | - Daniele Mendonça de Carvalho
73 | - Gabriel Lucas de Medeiros Leite
74 | - Gabriel Martins Spínola
75 | - Maria Luiza de Araújo Azevedo
76 |
77 | Notebook:
78 |
79 | [](https://colab.research.google.com/github/leobezerra/python-tads/blob/master/notebooks/list.ipynb)
80 | [](https://mybinder.org/v2/gh/leobezerra/python-tads/master)
81 |
82 | [Voltar para o índice](#índice)
83 |
84 | ---
85 |
86 | ### Listas ordenadas automaticamente
87 |
88 | Implementações:
89 | - Python: `sortedcontainers.SortedList`
90 | - C++: `set`, `multiset`
91 |
92 | Autores:
93 | - Álvaro Prudêncio Araújo
94 | - Felipe Rodrigues do Nascimento
95 | - Lindonilson de Oliveira Macial
96 | - Marcos Vinicio Araujo Delgado Junior
97 | - Yago Beserra Marques
98 |
99 | Notebook:
100 |
101 | [](https://colab.research.google.com/github/leobezerra/python-tads/blob/master/notebooks/SortedList.ipynb)
102 | [](https://mybinder.org/v2/gh/leobezerra/python-tads/master)
103 | [](https://youtu.be/I0hGOFS0Kd8)
104 |
105 | [Voltar para o índice](#índice)
106 |
107 | ---
108 |
109 | #### Pilhas
110 |
111 | Implementações:
112 | - Python: `queue.LifoQueue`
113 | - C++: `stack`
114 |
115 | Autores:
116 | - Abraão Lincol R. Cavalcante
117 | - Davi César de Araújo Bezerra
118 | - Emanuel Felipe G. Leão
119 | - João Vitor Dias Xavier
120 | - Lucas Vinicius Sales Dantas
121 |
122 | Notebook:
123 |
124 | [](https://colab.research.google.com/github/leobezerra/python-tads/blob/master/notebooks/LifoQueue.ipynb)
125 | [](https://mybinder.org/v2/gh/leobezerra/python-tads/master)
126 |
127 | [Voltar para o índice](#índice)
128 |
129 | ---
130 |
131 | ### Filas e deques
132 |
133 | Implementações:
134 | - Python: `queue.Queue`, `queue.PriorityQueue` e `collections.deque`
135 | - C++: `queue` e `deque`
136 |
137 | Autores:
138 | - Bruna Soares
139 | - Eduardo Paixão
140 | - Marlus Marcos
141 | - Pedro Nogueira
142 | - Rodolfo Dantas
143 |
144 | [](https://colab.research.google.com/github/leobezerra/python-tads/blob/master/notebooks/Queue-deque.ipynb)
145 | [](https://mybinder.org/v2/gh/leobezerra/python-tads/master)
146 |
147 | [Voltar para o índice](#índice)
148 |
149 | ---
150 |
151 | ### Árvores
152 |
153 | Implementações:
154 | - Python: milhões de bibliotecas 🤠 (`pptree`, por exemplo)
155 | - C++: bibliotecas (`Boost.PropertyTree`, por exemplo)
156 |
157 | Autores:
158 | - Felipe Eduardo
159 | - Fernando Igor
160 | - Italo Bruno
161 | - Keler Yohan
162 | - Leonardo Santos
163 |
164 | [](https://colab.research.google.com/github/leobezerra/python-tads/blob/master/notebooks/tree.ipynb)
165 | [](https://mybinder.org/v2/gh/leobezerra/python-tads/master)
166 |
167 | [Voltar para o índice](#índice)
168 |
169 | ---
170 |
171 | ### Consultas espaciais
172 |
173 | Implementações:
174 | - Python: `scipy.Spatial.KDTree`
175 | - C++: bibliotecas
176 |
177 | Autores:
178 | - Gabriel Rocha de Souza
179 | - Giovanna Karla de Macedo Felix
180 | - Jonas Florencio
181 | - João Paulo Carneiro
182 | - Pedro Cardoso Carvalho
183 |
184 | [](https://colab.research.google.com/github/leobezerra/python-tads/blob/master/notebooks/KdTree.ipynb)
185 | [](https://mybinder.org/v2/gh/leobezerra/python-tads/master)
186 |
187 | [Voltar para o índice](#índice)
188 |
189 |
--------------------------------------------------------------------------------
/notebooks/.ipynb_checkpoints/01-checkpoint.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "colab_type": "text",
7 | "id": "ilOE4mE2F1E1"
8 | },
9 | "source": [
10 | "# Conjuntos"
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "metadata": {
16 | "colab_type": "text",
17 | "id": "xLuXhXixIRB7"
18 | },
19 | "source": [
20 | "Uma pesquisa foi realizada com os alunos de uma turma de Tecnologia da Informação, perguntando quais idiomas cada aluno falava, dentre inglês, espanhol, francês e alemão.\n",
21 | "\n",
22 | "Com os resultados coletados, deseja-se saber quantos alunos falam somente um idioma. Considerando que a turma tinha apenas 30 alunos, talvez fosse fácil alcançar tal objetivo.\n",
23 | "\n",
24 | "Agora, suponha que essa mesma pesquisa fosse aplicada para todos os alunos da UFRN? E se considerássemos todos os campi da UFRN?\n",
25 | "\n",
26 | "É aí que entram os conjuntos!\n",
27 | "\n",
28 | "Os conjuntos são tipos abstratos de dados (equivalente aos conjuntos matemáticos) que manipulam coleções de elementos únicos, não ordenados e imutáveis."
29 | ]
30 | },
31 | {
32 | "cell_type": "markdown",
33 | "metadata": {
34 | "colab_type": "text",
35 | "id": "oaRQcnnIF_ij"
36 | },
37 | "source": [
38 | "## Primeiros passos"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {
44 | "colab_type": "text",
45 | "id": "ND1SNBnpIwLt"
46 | },
47 | "source": [
48 | "Em Python, um conjunto pode ser criado já com seus elementos declarados, dentro de chaves {} e separando-os por vírgulas.\n",
49 | "\n",
50 | "Também é possível criar um conjunto vazio, com a função construtora ```set()```:"
51 | ]
52 | },
53 | {
54 | "cell_type": "code",
55 | "execution_count": null,
56 | "metadata": {
57 | "colab": {},
58 | "colab_type": "code",
59 | "id": "oi9nn22uIzjb"
60 | },
61 | "outputs": [],
62 | "source": [
63 | "meu_conjunto = {1, 2, 3, 4, 5}\n",
64 | "conjunto_vazio = set()\n",
65 | "\n",
66 | "print(meu_conjunto)\n",
67 | "print(conjunto_vazio)"
68 | ]
69 | },
70 | {
71 | "cell_type": "markdown",
72 | "metadata": {
73 | "colab_type": "text",
74 | "id": "EhoNN5CHJp01"
75 | },
76 | "source": [
77 | "Um conjunto pode ter elementos de diferentes tipos:"
78 | ]
79 | },
80 | {
81 | "cell_type": "code",
82 | "execution_count": null,
83 | "metadata": {
84 | "colab": {},
85 | "colab_type": "code",
86 | "id": "9pyi5-BDJtbW"
87 | },
88 | "outputs": [],
89 | "source": [
90 | "meu_conjunto = {1, 3.3, 'a', 'palavra'}\n",
91 | "print(meu_conjunto)"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {
97 | "colab_type": "text",
98 | "id": "LXrM-DDVKEhx"
99 | },
100 | "source": [
101 | "Além disso, um conjunto pode ser criado com a função construtora ```set()``` tendo como parâmetro um tipo iterável de dados (string, lista, dicionário, tuplas, etc...). \n",
102 | "\n",
103 | "Nesse caso, o conjunto formado possui os elementos únicos do tipo iterávels fornecido como parâmetro:"
104 | ]
105 | },
106 | {
107 | "cell_type": "code",
108 | "execution_count": null,
109 | "metadata": {
110 | "colab": {},
111 | "colab_type": "code",
112 | "id": "kSvywhQAKQjz"
113 | },
114 | "outputs": [],
115 | "source": [
116 | "meu_conjunto = set('Hello,world')\n",
117 | "print(meu_conjunto)"
118 | ]
119 | },
120 | {
121 | "cell_type": "markdown",
122 | "metadata": {},
123 | "source": [
124 | "### Iterando sobre seus elementos"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "metadata": {},
130 | "source": [
131 | "Você pode iterar sobre os elementos de um conjunto usando um `for`:"
132 | ]
133 | },
134 | {
135 | "cell_type": "code",
136 | "execution_count": null,
137 | "metadata": {},
138 | "outputs": [],
139 | "source": [
140 | "for x in meu_conjunto:\n",
141 | " print(x)"
142 | ]
143 | },
144 | {
145 | "cell_type": "markdown",
146 | "metadata": {},
147 | "source": [
148 | "Como não há preservação de ordem dos elementos de um `set`, você não pode acessar seus elementos por índices ou confiar em qual ordem eles estarão:"
149 | ]
150 | },
151 | {
152 | "cell_type": "code",
153 | "execution_count": null,
154 | "metadata": {},
155 | "outputs": [],
156 | "source": [
157 | "meu_conjunto[0]"
158 | ]
159 | },
160 | {
161 | "cell_type": "markdown",
162 | "metadata": {
163 | "colab_type": "text",
164 | "id": "sO4uG468TeYY"
165 | },
166 | "source": [
167 | "#### Exercícios w3r - [w3resource list](https://www.w3resource.com/python-exercises/python-functions-exercises.php)"
168 | ]
169 | },
170 | {
171 | "cell_type": "markdown",
172 | "metadata": {
173 | "colab_type": "text",
174 | "id": "1jkEksPIU02F"
175 | },
176 | "source": [
177 | "1 - Escreva um procedimento que determine o maior número dentro de um conjunto de 7 números."
178 | ]
179 | },
180 | {
181 | "cell_type": "code",
182 | "execution_count": null,
183 | "metadata": {
184 | "colab": {},
185 | "colab_type": "code",
186 | "id": "P5mpbHUnVQok"
187 | },
188 | "outputs": [],
189 | "source": []
190 | },
191 | {
192 | "cell_type": "markdown",
193 | "metadata": {
194 | "colab_type": "text",
195 | "id": "roGVGDLhVubL"
196 | },
197 | "source": [
198 | "2 - Escreva um procedimento que some todos os elementos de um conjunto."
199 | ]
200 | },
201 | {
202 | "cell_type": "code",
203 | "execution_count": null,
204 | "metadata": {
205 | "colab": {},
206 | "colab_type": "code",
207 | "id": "h4V_VlBtV13T"
208 | },
209 | "outputs": [],
210 | "source": []
211 | },
212 | {
213 | "cell_type": "markdown",
214 | "metadata": {
215 | "colab_type": "text",
216 | "id": "R7DdPaF8V2ny"
217 | },
218 | "source": [
219 | "3 - Escreva um procedimento que multiplique todos os elementos de um conjunto."
220 | ]
221 | },
222 | {
223 | "cell_type": "code",
224 | "execution_count": null,
225 | "metadata": {},
226 | "outputs": [],
227 | "source": []
228 | },
229 | {
230 | "cell_type": "markdown",
231 | "metadata": {},
232 | "source": [
233 | "> Como os exercícios acima são bem comuns no dia-a-dia, Python tem procedimentos-padrão para resolvê-los. Pesquise sobre eles e veja como fica bem mais simples de resolver essas questões 👍🏻"
234 | ]
235 | },
236 | {
237 | "cell_type": "markdown",
238 | "metadata": {
239 | "colab_type": "text",
240 | "id": "y38humahGCyX"
241 | },
242 | "source": [
243 | "## Como usar o `set`"
244 | ]
245 | },
246 | {
247 | "cell_type": "markdown",
248 | "metadata": {
249 | "colab_type": "text",
250 | "id": "MPksi_HuLOKV"
251 | },
252 | "source": [
253 | "### Adição e remoção de elementos \n",
254 | "\n",
255 | "Depois de ser criado, um conjunto pode ser modificado, tendo elementos adicionados ou removidos dele.\n",
256 | "\n",
257 | "Para adicionar um elemento, utiliza-se o método ```add()```. \n",
258 | "\n",
259 | "> Confira na sessão de **Extras** os comandos `update` para adição de múltiplos elementos."
260 | ]
261 | },
262 | {
263 | "cell_type": "code",
264 | "execution_count": null,
265 | "metadata": {
266 | "colab": {},
267 | "colab_type": "code",
268 | "id": "4rRjt12NLQjF"
269 | },
270 | "outputs": [],
271 | "source": [
272 | "meu_conjunto = {1, 2, 3}\n",
273 | "meu_conjunto.add(4)\n",
274 | "print(meu_conjunto)"
275 | ]
276 | },
277 | {
278 | "cell_type": "markdown",
279 | "metadata": {
280 | "colab_type": "text",
281 | "id": "AEfOVzgmLel7"
282 | },
283 | "source": [
284 | "Já para remover, tem-se o método ```remove()```, que elimina do conjunto o elemento passado como parâmetro:"
285 | ]
286 | },
287 | {
288 | "cell_type": "code",
289 | "execution_count": null,
290 | "metadata": {
291 | "colab": {},
292 | "colab_type": "code",
293 | "id": "zuRXcU69LoLI"
294 | },
295 | "outputs": [],
296 | "source": [
297 | "meu_conjunto = {1, 2, 3}\n",
298 | "meu_conjunto.remove(3)\n",
299 | "print(meu_conjunto) "
300 | ]
301 | },
302 | {
303 | "cell_type": "markdown",
304 | "metadata": {
305 | "colab_type": "text",
306 | "id": "aQ69iaVnL8xR"
307 | },
308 | "source": [
309 | "E, se por algum motivo, o usuário tentar remover um elemento que não existe no conjunto?"
310 | ]
311 | },
312 | {
313 | "cell_type": "code",
314 | "execution_count": null,
315 | "metadata": {
316 | "colab": {},
317 | "colab_type": "code",
318 | "id": "PqpKn982L9nt"
319 | },
320 | "outputs": [],
321 | "source": [
322 | "meu_conjunto = {1, 2, 3}\n",
323 | "meu_conjunto.remove(4)\n",
324 | "print(meu_conjunto) "
325 | ]
326 | },
327 | {
328 | "cell_type": "markdown",
329 | "metadata": {
330 | "colab_type": "text",
331 | "id": "kvUgGNk2MEn5"
332 | },
333 | "source": [
334 | "Você recebeu o erro `KeyError`, justamente porque o `remove()` só remove elementos que fazem parte do conjunto. \n",
335 | "\n",
336 | "Para essa situação, existe o método `discard()`, que tenta remover um elemento sem disparar erros caso ele não exista."
337 | ]
338 | },
339 | {
340 | "cell_type": "code",
341 | "execution_count": null,
342 | "metadata": {
343 | "colab": {},
344 | "colab_type": "code",
345 | "id": "e5zb9PrhMbIz"
346 | },
347 | "outputs": [],
348 | "source": [
349 | "meu_conjunto = {1, 2, 3}\n",
350 | "meu_conjunto.discard(2)\n",
351 | "print(meu_conjunto) \n",
352 | "meu_conjunto.discard(4)\n",
353 | "print(meu_conjunto) "
354 | ]
355 | },
356 | {
357 | "cell_type": "markdown",
358 | "metadata": {
359 | "colab_type": "text",
360 | "id": "YM2I76jGMmgU"
361 | },
362 | "source": [
363 | "Também existe o método `clear()`, que remove todos os elementos do conjunto:"
364 | ]
365 | },
366 | {
367 | "cell_type": "code",
368 | "execution_count": null,
369 | "metadata": {
370 | "colab": {},
371 | "colab_type": "code",
372 | "id": "GJN1pENNMoC9"
373 | },
374 | "outputs": [],
375 | "source": [
376 | "meu_conjunto = {1, 2, 3}\n",
377 | "print(meu_conjunto)\n",
378 | "meu_conjunto.clear()\n",
379 | "print(meu_conjunto) "
380 | ]
381 | },
382 | {
383 | "cell_type": "markdown",
384 | "metadata": {
385 | "colab_type": "text",
386 | "id": "_rqm_nCuNHR7"
387 | },
388 | "source": [
389 | "### Cardinalidade \n",
390 | "\n",
391 | "O número de elementos de um conjunto pode ser calculado com o procedimento `len()`:"
392 | ]
393 | },
394 | {
395 | "cell_type": "code",
396 | "execution_count": null,
397 | "metadata": {
398 | "colab": {},
399 | "colab_type": "code",
400 | "id": "dWl_Bzd6NJgW"
401 | },
402 | "outputs": [],
403 | "source": [
404 | "meu_conjunto = {1, 2, 3}\n",
405 | "print (len(meu_conjunto))"
406 | ]
407 | },
408 | {
409 | "cell_type": "markdown",
410 | "metadata": {
411 | "colab_type": "text",
412 | "id": "5r_4F-SzHlWC"
413 | },
414 | "source": [
415 | "### União\n",
416 | "\n",
417 | "Assim como na matemática, a união de `sets` concatena os elementos dos conjuntos em questão em um só.\n",
418 | "\n",
419 | "Em Python, a operação é realizada através do método `union()` ou do operador `|`.\n",
420 | "\n",
421 | "> A união de conjuntos significa literalmente identificar os elementos presentes em um conjunto **ou** no outro. É por isso que podemos usar o operador lógico `|` 🙃 \n",
422 | "\n",
423 | "No exemplo abaixo, temos dois conjuntos distintos `a` e `b` que desejamos unir:"
424 | ]
425 | },
426 | {
427 | "cell_type": "code",
428 | "execution_count": null,
429 | "metadata": {
430 | "colab": {},
431 | "colab_type": "code",
432 | "id": "SGT6bQNbHudf"
433 | },
434 | "outputs": [],
435 | "source": [
436 | "a = {1, 2, 3, 4}\n",
437 | "b = {3, 4, 5, 6}\n",
438 | "\n",
439 | "# operando com union()\n",
440 | "print(a.union(b))\n",
441 | "\n",
442 | "# operando com |\n",
443 | "print(a | b)"
444 | ]
445 | },
446 | {
447 | "cell_type": "markdown",
448 | "metadata": {
449 | "colab_type": "text",
450 | "id": "tJkYrP_QISog"
451 | },
452 | "source": [
453 | "### Intersecção\n",
454 | "\n",
455 | "Fazendo a interseção entre dois `sets`, obtemos o conjunto de elementos em comum entre eles.\n",
456 | "\n",
457 | "Podemos realizar essa operação através do método `intersection()` ou do operador `&`.\n",
458 | "\n",
459 | "> A intersecção de conjuntos significa literalmente identificar os elementos presentes em um conjunto **e** no outro. É por isso que podemos usar o operador lógico `&` 🙃 "
460 | ]
461 | },
462 | {
463 | "cell_type": "code",
464 | "execution_count": null,
465 | "metadata": {
466 | "colab": {},
467 | "colab_type": "code",
468 | "id": "l68oYejMIe-7"
469 | },
470 | "outputs": [],
471 | "source": [
472 | "# operando com intersection()\n",
473 | "print(a.intersection(b))\n",
474 | "\n",
475 | "#operando com &\n",
476 | "print(a & b)"
477 | ]
478 | },
479 | {
480 | "cell_type": "markdown",
481 | "metadata": {
482 | "colab_type": "text",
483 | "id": "cE5JZpt1IlJv"
484 | },
485 | "source": [
486 | "### Diferença\n",
487 | "\n",
488 | "Com a diferença entre `a` e `b`, obtemos o conjunto de elementos que pertencem ao conjunto `a`, mas não pertencem ao conjunto `b`.\n",
489 | "\n",
490 | "Realizamos esta operação usando o método `difference()` ou o operador `-`. \n",
491 | "\n",
492 | "**Note que `a - b` não é necessariamente igual a `b - a`.**\n",
493 | "\n",
494 | "> A diferença de conjuntos significa literalmente identificar os elementos presentes em um conjunto, **menos** os que estejam no outro. É por isso que podemos usar o operador aritmético `-` 🙃 "
495 | ]
496 | },
497 | {
498 | "cell_type": "code",
499 | "execution_count": null,
500 | "metadata": {
501 | "colab": {},
502 | "colab_type": "code",
503 | "id": "uFDjRpwsI1E2"
504 | },
505 | "outputs": [],
506 | "source": [
507 | "# operando com difference()\n",
508 | "print(a.difference(b))\n",
509 | "print(b.difference(a))\n",
510 | "\n",
511 | "# operando com -\n",
512 | "print(a - b)\n",
513 | "print(b - a)"
514 | ]
515 | },
516 | {
517 | "cell_type": "markdown",
518 | "metadata": {
519 | "colab_type": "text",
520 | "id": "XPfzCP-xI61N"
521 | },
522 | "source": [
523 | "### Diferença simétrica\n",
524 | "\n",
525 | "A diferença simétrica representa a união dos elementos de dois conjuntos, com exceção daqueles que estejam na intersecção entre estes dois conjuntos.\n",
526 | "\n",
527 | "É possível realizar esta operação através do método `symmetric_difference()` ou do operador `^`.\n",
528 | "\n",
529 | "> A diferença simétrica de conjuntos significa literalmente identificar os elementos presentes **ou** em um conjunto **ou** no outro. É por isso que podemos usar o operador lógico `^`, que representa o **ou exclusivo** 🙃 "
530 | ]
531 | },
532 | {
533 | "cell_type": "code",
534 | "execution_count": null,
535 | "metadata": {
536 | "colab": {},
537 | "colab_type": "code",
538 | "id": "rVty_0EcJBug"
539 | },
540 | "outputs": [],
541 | "source": [
542 | "# operando com symmetric_difference()\n",
543 | "print(a.symmetric_difference(b))\n",
544 | "\n",
545 | "# operando com ^\n",
546 | "print(a ^ b)"
547 | ]
548 | },
549 | {
550 | "cell_type": "markdown",
551 | "metadata": {
552 | "colab_type": "text",
553 | "id": "VlxTDCtWJbyd"
554 | },
555 | "source": [
556 | "### Pertinência\n",
557 | "\n",
558 | "Utilizando o operador de pertinência `in`, podemos verificar se um elemento está ou não em um conjunto:"
559 | ]
560 | },
561 | {
562 | "cell_type": "code",
563 | "execution_count": null,
564 | "metadata": {
565 | "colab": {},
566 | "colab_type": "code",
567 | "id": "s_szy9T1Jf0V"
568 | },
569 | "outputs": [],
570 | "source": [
571 | "1 in a"
572 | ]
573 | },
574 | {
575 | "cell_type": "code",
576 | "execution_count": null,
577 | "metadata": {
578 | "colab": {},
579 | "colab_type": "code",
580 | "id": "rVWrE64JJv8z"
581 | },
582 | "outputs": [],
583 | "source": [
584 | "5 in a"
585 | ]
586 | },
587 | {
588 | "cell_type": "markdown",
589 | "metadata": {},
590 | "source": [
591 | "Também podemos combinar o operador `in` com o operador lógico `not`:"
592 | ]
593 | },
594 | {
595 | "cell_type": "code",
596 | "execution_count": null,
597 | "metadata": {
598 | "colab": {},
599 | "colab_type": "code",
600 | "id": "NFFeJzOnQSoj"
601 | },
602 | "outputs": [],
603 | "source": [
604 | "8 not in a"
605 | ]
606 | },
607 | {
608 | "cell_type": "markdown",
609 | "metadata": {},
610 | "source": [
611 | "### Continência e disjunção"
612 | ]
613 | },
614 | {
615 | "cell_type": "markdown",
616 | "metadata": {
617 | "colab_type": "text",
618 | "id": "utuzvdZyKk-L"
619 | },
620 | "source": [
621 | "Enquanto o operador `in` verifica se um elemento pertence a um conjunto, o `set` oferece três métodos para testar relações entre conjuntos: "
622 | ]
623 | },
624 | {
625 | "cell_type": "markdown",
626 | "metadata": {},
627 | "source": [
628 | "1. `issubset()` ou `<=`: testa se um conjunto está contido em outro, ou seja, se um conjunto é um subconjunto do outro."
629 | ]
630 | },
631 | {
632 | "cell_type": "code",
633 | "execution_count": null,
634 | "metadata": {
635 | "colab": {},
636 | "colab_type": "code",
637 | "id": "C7509kyLKpn-"
638 | },
639 | "outputs": [],
640 | "source": [
641 | "c = {1, 2}\n",
642 | "\n",
643 | "# operando com issubset()\n",
644 | "if c.issubset(a): \n",
645 | " print(\"C é subconjunto de A, pois C está contido em A.\")\n",
646 | "else:\n",
647 | " print(\"C não é subconjunto de A, pois C não está contido em A.\")\n",
648 | "\n",
649 | "# operando com <=\n",
650 | "if not c <= a: \n",
651 | " print(\"C não é subconjunto de A, pois C não está contido em A.\")\n",
652 | "else:\n",
653 | " print(\"C é subconjunto de A, pois C está contido em A.\")"
654 | ]
655 | },
656 | {
657 | "cell_type": "markdown",
658 | "metadata": {
659 | "colab_type": "text",
660 | "id": "NK1SRkIyK3sG"
661 | },
662 | "source": [
663 | "2. `issuperset()` ou `>=`: testa se um conjunto contém o outro, ou seja, se um conjunto é um superconjunto do outro."
664 | ]
665 | },
666 | {
667 | "cell_type": "code",
668 | "execution_count": null,
669 | "metadata": {
670 | "colab": {},
671 | "colab_type": "code",
672 | "id": "7eaiyrLfLCsF"
673 | },
674 | "outputs": [],
675 | "source": [
676 | "# operando com issuperset()\n",
677 | "if a.issuperset(c):\n",
678 | " print(\"A é superconjunto de C, pois A contém C.\")\n",
679 | "else:\n",
680 | " print(\"A não é superconjunto de C, pois A não contém C.\")\n",
681 | " \n",
682 | "# operando com >=\n",
683 | "if not a >= c:\n",
684 | " print(\"A não é superconjunto de C, pois A não contém C.\")\n",
685 | "else:\n",
686 | " print(\"A é superconjunto de C, pois A contém C.\")"
687 | ]
688 | },
689 | {
690 | "cell_type": "markdown",
691 | "metadata": {},
692 | "source": [
693 | "> As relações `<=` e `>=` são simétricas, então `a >= b` equivale a `b <= a`."
694 | ]
695 | },
696 | {
697 | "cell_type": "markdown",
698 | "metadata": {
699 | "colab_type": "text",
700 | "id": "9QjPx2nZMOgj"
701 | },
702 | "source": [
703 | "3. `isdisjoint()`: testa se dois conjuntos são disjuntos, ou seja, se a interseção entre eles é vazia."
704 | ]
705 | },
706 | {
707 | "cell_type": "code",
708 | "execution_count": null,
709 | "metadata": {
710 | "colab": {},
711 | "colab_type": "code",
712 | "id": "dcknyU00MUa2"
713 | },
714 | "outputs": [],
715 | "source": [
716 | "if c.isdisjoint(a):\n",
717 | " print(\"C e A são disjuntos, pois sua interseção é vazia.\")\n",
718 | "else:\n",
719 | " print(\"C e A não são disjuntos, pois sua interseção não é vazia.\")\n",
720 | "if c.isdisjoint(b):\n",
721 | " print(\"C e B são disjuntos, pois sua interseção é vazia.\")\n",
722 | "else:\n",
723 | " print(\"C e B não são disjuntos, pois sua interseção não é vazia.\")"
724 | ]
725 | },
726 | {
727 | "cell_type": "markdown",
728 | "metadata": {
729 | "colab_type": "text",
730 | "id": "va2_qr9VRCxm"
731 | },
732 | "source": [
733 | "# Exercícios"
734 | ]
735 | },
736 | {
737 | "cell_type": "markdown",
738 | "metadata": {
739 | "colab_type": "text",
740 | "id": "0ZrVKl2LRHPn"
741 | },
742 | "source": [
743 | "1 - Agora que já temos um bom conhecimentos sobre os conjuntos, voltemos ao exemplo da introdução. \n",
744 | "\n",
745 | "Os dados sobre conhecimento em diversos idiomas pelos estudantes da UFRN são guardados em um banco de dados. \n",
746 | "\n",
747 | "Após consulta a essa base de dados, a matrícula dos alunos foram salvas nos conjuntos relativos aos idiomas que cada um fala:"
748 | ]
749 | },
750 | {
751 | "cell_type": "code",
752 | "execution_count": null,
753 | "metadata": {
754 | "colab": {},
755 | "colab_type": "code",
756 | "id": "YgOmzQPrRdHa"
757 | },
758 | "outputs": [],
759 | "source": [
760 | "ingles = {2017992691, 2014731077, 2016127320, 2017673650, 2017675600, 2016071490, 2015763941,2018124856, 2014240183, 2015069118, 2017397627, 2018257434, 2018146279,2018336479, 2016255160, 2016191681, 2017462010, 2015267990, 2018353177,2016316106, 2017534024, 2017435227, 2018485174, 2017511916, 2018252953, 2018230360, 2015896310, 2016403233, 2018036952, 2018223748, 2017106407, 2018928865, 2015808443, 2015490023, 2014680801, 2016797947, 2017169550, 2017741705, 2016449433, 2018701674, 2018681674, 2018822119, 2015629894, 2018552429, 2014160569, 2014812342, 2015241433, 2015633224, 2015938370, 2014994808, 2018682286, 2014920254, 2017952048, 2014899143, 2018459199, 2015659561, 2018886010, 2016111302, 2018528579, 2017559038, 2018248638, 2015560871, 2014569332, 2018652276, 2016701261, 2016308042, 2016310173, 2017705448, 2014399415, 2016268450, 2017608181, 2015981561, 2014964705, 2014655030, 2017687958, 2016162852, 2017223176, 2014759427, 2017290535, 2017031946, 2017042504, 2018916372, 2017757689, 2014922487, 2016080164, 2014792539, 2016110301, 2015200433, 2015667306, 2014891106, 2014748251, 2018911399, 2015008915, 2014976823, 2018870448}\n",
761 | "espanhol = {2017992691, 2014731077, 2016127320, 2017673650, 2017675600, 2016071490, 2015763941, 2015365994, 2014728861, 2014152867, 2018044073, 2015856913, 2018124856, 2014240183, 2017534024, 2017435227, 2018485174, 2017511916, 2018252953, 2018230360, 2015896310, 2016403233, 2018036952, 2018223748, 2017106407, 2018928865, 2015808443, 2015490023, 2014680801, 2016797947, 2017169550, 2017741705, 2016449433, 2018701674, 2018681674, 2018822119, 2015629894, 2018552429, 2014160569, 2014812342, 2015241433, 2015633224, 2015938370, 2014994808, 2018682286, 2014920254, 2017952048, 2014899143, 2018459199, 2015659561, 2018886010, 2016111302, 2018528579, 2017559038, 2018248638, 2015560871, 2014569332, 2018652276, 2016701261, 2016308042, 2016310173, 2017705448, 2014399415, 2016268450}\n",
762 | "frances = {2016268450, 2017608181, 2015981561, 2014964705, 2014655030, 2017687958, 2016162852, 2017223176, 2014759427, 2017290535, 2017031946, 2017042504, 2018916372, 2017757689, 2014922487, 2016080164, 2014792539, 2016110301, 2015200433, 2015667306, 2014891106, 2014748251, 2018911399, 2015008915, 2014976823, 2018870448, 2018230360, 2015896310, 2016403233, 2018036952, 2018223748, 2017106407, 2018928865, 2015808443, 2015490023, 2014680801, 2016797947, 2017169550, 2017741705, 2016449433, 2018701674, 2018681674, 2018822119, 2015629894, 2018552429,}\n",
763 | "alemao = {2015763941, 2015365994, 2014728861, 2014152867, 2018044073, 2015856913, 2018124856, 2014240183, 2015069118, 2017397627, 2018257434, 2018146279,2018336479, 2016255160, 2016191681, 2017462010, 2015267990, 2018353177,2016316106, 2017534024, 2017435227, 2018485174, 2017511916, 2018252953, 2018230360, 2015896310, 2016403233, 2018036952, 2018223748, 2017106407, 2018928865, 2015808443, 2015490023, 2014680801, 2016797947, 2017169550, 2017741705, 2016449433, 2018701674, 2018681674, 2018822119, 2015629894, 2018552429, 2014160569, 2014812342, 2015241433, 2015633224, 2015938370, 2014994808, 2018682286, 2014920254}"
764 | ]
765 | },
766 | {
767 | "cell_type": "markdown",
768 | "metadata": {
769 | "colab_type": "text",
770 | "id": "ZP7aLZTtRrBs"
771 | },
772 | "source": [
773 | "1.1 - Calcule quantos alunos falam apenas inglês e espanhol:"
774 | ]
775 | },
776 | {
777 | "cell_type": "code",
778 | "execution_count": null,
779 | "metadata": {
780 | "colab": {},
781 | "colab_type": "code",
782 | "id": "cOpD-g4aRsQB"
783 | },
784 | "outputs": [],
785 | "source": []
786 | },
787 | {
788 | "cell_type": "markdown",
789 | "metadata": {
790 | "colab_type": "text",
791 | "id": "EAbcOQ2DRv4A"
792 | },
793 | "source": [
794 | "1.2 - Calcule quantos alunos falam apenas um idioma:"
795 | ]
796 | },
797 | {
798 | "cell_type": "code",
799 | "execution_count": null,
800 | "metadata": {
801 | "colab": {},
802 | "colab_type": "code",
803 | "id": "I0XlgJdrR0Ve"
804 | },
805 | "outputs": [],
806 | "source": []
807 | },
808 | {
809 | "cell_type": "markdown",
810 | "metadata": {
811 | "colab_type": "text",
812 | "id": "Z_HROn0QRs_W"
813 | },
814 | "source": [
815 | "1.3 - Calcule quantos alunos falam dois idiomas:"
816 | ]
817 | },
818 | {
819 | "cell_type": "code",
820 | "execution_count": null,
821 | "metadata": {
822 | "colab": {},
823 | "colab_type": "code",
824 | "id": "TmNx8vBCRz1I"
825 | },
826 | "outputs": [],
827 | "source": []
828 | },
829 | {
830 | "cell_type": "markdown",
831 | "metadata": {
832 | "colab_type": "text",
833 | "id": "Bx2KGgZKSKKR"
834 | },
835 | "source": [
836 | "Já imaginou realizar esses cálculos sem o ```set()```? Com certeza, teríamos mais trabalho.\n",
837 | "\n",
838 | "Nesse exercício, vimos uma das utilidades dos conjuntos, que é realizar operações. Outra ocasião em que pode ser bastante útil é na remoção de elementos repetidos de uma sequência. Para entender melhor, faça o exercício 2:"
839 | ]
840 | },
841 | {
842 | "cell_type": "markdown",
843 | "metadata": {
844 | "colab_type": "text",
845 | "id": "GsztDDtzSLUQ"
846 | },
847 | "source": [
848 | "2 - **[OBI - 2012]** Certa vez, numa aula, a professora passou um filme para os alunos assistirem. Durante este filme, ela passou uma lista de presença em sua sala para verificar a presença dos alunos, onde cada aluno deveria inserir apenas seu número de registro. Alguns alunos contudo, como possuem amigos que fogem da aula, decidiram ser camaradas e inseriram os números de registro de seus amigos fujões. O problema é que muitos alunos são amigos de alunos que fogem da aula e alguns números de registro acabaram sendo repetidamente inseridos na lista de presença. Além de tudo, alguns dos alunos que se esperava que não estivessem na aula de fato estavam!\n",
849 | "\n",
850 | "A professora, ao notar que a lista de presença continha alguns números repetidos, ficou sem entender, mas decidiu dar um voto de confiança e dar presença a todos os alunos cujos números de registro estavam na lista. Como são muitos alunos na sala e muitos números com repetição, ela pediu a sua ajuda para determinar o total de alunos que receberam presença na aula."
851 | ]
852 | },
853 | {
854 | "cell_type": "markdown",
855 | "metadata": {
856 | "colab_type": "text",
857 | "id": "WpucsZKZS7Sn"
858 | },
859 | "source": [
860 | "**Entrada**\n",
861 | "\n",
862 | "A primeira linha da entrada contém um número inteiro N , que informa a quantidade de números de registro que apareceram na lista de presença. Cada uma das N linhas seguintes contém um número de registro Vi que foi inserido na lista de presença.\n",
863 | "\n",
864 | "**Saída**\n",
865 | "Seu programa deve imprimir uma única linha, contendo apenas um número inteiro, o número de alunos que receberam presença."
866 | ]
867 | },
868 | {
869 | "cell_type": "markdown",
870 | "metadata": {
871 | "colab_type": "text",
872 | "id": "ptPTsS7kTRyu"
873 | },
874 | "source": [
875 | "| Entrada \t| Saída \t|\n",
876 | "|--------------------\t|-------\t|\n",
877 | "| 3
2
3
1| 3 \t|"
878 | ]
879 | },
880 | {
881 | "cell_type": "code",
882 | "execution_count": null,
883 | "metadata": {
884 | "colab": {},
885 | "colab_type": "code",
886 | "id": "q7GEc59NTeVk"
887 | },
888 | "outputs": [],
889 | "source": []
890 | },
891 | {
892 | "cell_type": "markdown",
893 | "metadata": {
894 | "colab_type": "text",
895 | "id": "hGQloYI5TfFe"
896 | },
897 | "source": [
898 | "3 - **[Continuação]** No dia seguinte, a professora deu um grande sermão para os seus alunos, que se comprometeram a não fugir mais das aulas.\n",
899 | "Passada uma semana, a professora passou mais um filme para os seus alunos assistirem e a mesma situação se repetiu. Chateada, ela decidiu que, dessa vez, daria falta nos alunos que tinham registro repetido na lista de presença. Mais uma vez, ela pediu a sua ajuda para determinar o total de alunos que receberam presença na aula."
900 | ]
901 | },
902 | {
903 | "cell_type": "markdown",
904 | "metadata": {
905 | "colab_type": "text",
906 | "id": "MxbSUPtcTpSQ"
907 | },
908 | "source": [
909 | "**Entrada**\n",
910 | "\n",
911 | "A primeira linha da entrada contém um número inteiro N , que informa a quantidade de números de registro que apareceram na lista de presença. Cada uma das N linhas seguintes contém um número de registro Vi que foi inserido na lista de presença.\n",
912 | "\n",
913 | "**Saída**\n",
914 | "\n",
915 | "Seu programa deve imprimir uma única linha, contendo apenas um número inteiro, o número de alunos que receberam presença.\n"
916 | ]
917 | },
918 | {
919 | "cell_type": "markdown",
920 | "metadata": {
921 | "colab_type": "text",
922 | "id": "R3BU7OJbTyJq"
923 | },
924 | "source": [
925 | "| Entrada \t| Saída \t|\n",
926 | "|--------------------\t| -------\t|\n",
927 | "| 15
1
0
5
6
0
12
25
6
2
6
5
0
25
13
2 | 4 \t|"
928 | ]
929 | },
930 | {
931 | "cell_type": "code",
932 | "execution_count": null,
933 | "metadata": {
934 | "colab": {},
935 | "colab_type": "code",
936 | "id": "3YeNjIU4LC3C"
937 | },
938 | "outputs": [],
939 | "source": []
940 | },
941 | {
942 | "cell_type": "markdown",
943 | "metadata": {
944 | "colab_type": "text",
945 | "id": "G21D68zTU3Vd"
946 | },
947 | "source": [
948 | "3 - João e Maria possuem um dado de 12 faces e gostam de jogar com ele da seguinte forma:\n",
949 | "- João lança o dado e o número da face virada para cima é eliminado;\n",
950 | "- depois, Maria repete o processo. Caso tire um número que já foi eliminado, nada acontece;\n",
951 | "- assim continuam até que não restem mais números para serem eliminados;\n",
952 | "- ganha quem conseguir eliminar o último número.
\n",
953 | "Faça um programa que simule esse jogo"
954 | ]
955 | },
956 | {
957 | "cell_type": "code",
958 | "execution_count": null,
959 | "metadata": {
960 | "colab": {},
961 | "colab_type": "code",
962 | "id": "abFSN0BPWQcp"
963 | },
964 | "outputs": [],
965 | "source": []
966 | },
967 | {
968 | "cell_type": "markdown",
969 | "metadata": {
970 | "colab_type": "text",
971 | "id": "twjw_hF1N24I"
972 | },
973 | "source": [
974 | "# Extras"
975 | ]
976 | },
977 | {
978 | "cell_type": "markdown",
979 | "metadata": {
980 | "colab_type": "text",
981 | "id": "hBuv6GdgUXyX"
982 | },
983 | "source": [
984 | "**Update**: Modifica o conjunto A para possuir os elementos de A $\\cup$ B"
985 | ]
986 | },
987 | {
988 | "cell_type": "code",
989 | "execution_count": null,
990 | "metadata": {
991 | "colab": {},
992 | "colab_type": "code",
993 | "id": "jGYVaBaTUkf3"
994 | },
995 | "outputs": [],
996 | "source": [
997 | "a = {1, 2, 3, 4}\n",
998 | "b = {3, 4, 5, 6}\n",
999 | "print(a)\n",
1000 | "print(b)\n",
1001 | "print(a.union(b))\n",
1002 | "a.update(b)\n",
1003 | "print(a)\n",
1004 | "print(b)"
1005 | ]
1006 | },
1007 | {
1008 | "cell_type": "markdown",
1009 | "metadata": {
1010 | "colab_type": "text",
1011 | "id": "UznGU1E6Uv4j"
1012 | },
1013 | "source": [
1014 | "A função ```update()``` pode ser utilizada com outras funções, sendo escrita como sufixo. \n",
1015 | "\n",
1016 | "Nesse caso, ela sobrescreve o conjunto A para ser equivalente a operação desejada. \n",
1017 | "\n",
1018 | "Por exemplo:"
1019 | ]
1020 | },
1021 | {
1022 | "cell_type": "code",
1023 | "execution_count": null,
1024 | "metadata": {
1025 | "colab": {},
1026 | "colab_type": "code",
1027 | "id": "q0XJwlsPUyxF"
1028 | },
1029 | "outputs": [],
1030 | "source": [
1031 | "a = {1, 2, 3, 4}\n",
1032 | "b = {3, 4, 5, 6}\n",
1033 | "print(a)\n",
1034 | "print(b)\n",
1035 | "print(a.intersection(b))\n",
1036 | "a.intersection_update(b)\n",
1037 | "print(a)\n",
1038 | "print(b)"
1039 | ]
1040 | },
1041 | {
1042 | "cell_type": "code",
1043 | "execution_count": null,
1044 | "metadata": {
1045 | "colab": {},
1046 | "colab_type": "code",
1047 | "id": "FzOkoEYSelGa"
1048 | },
1049 | "outputs": [],
1050 | "source": [
1051 | "a = {1, 2, 3, 4}\n",
1052 | "b = {3, 4, 5, 6}\n",
1053 | "print(a)\n",
1054 | "print(b)\n",
1055 | "print(a.difference(b))\n",
1056 | "a.difference_update(b)\n",
1057 | "print(a)\n",
1058 | "print(b)"
1059 | ]
1060 | },
1061 | {
1062 | "cell_type": "code",
1063 | "execution_count": null,
1064 | "metadata": {
1065 | "colab": {},
1066 | "colab_type": "code",
1067 | "id": "TO7DCjp6elTr"
1068 | },
1069 | "outputs": [],
1070 | "source": [
1071 | "a = {1, 2, 3, 4}\n",
1072 | "b = {3, 4, 5, 6}\n",
1073 | "print(a)\n",
1074 | "print(b)\n",
1075 | "print(a.symmetric_difference(b))\n",
1076 | "a.symmetric_difference_update(b)\n",
1077 | "print(a)\n",
1078 | "print(b)"
1079 | ]
1080 | },
1081 | {
1082 | "cell_type": "markdown",
1083 | "metadata": {
1084 | "colab_type": "text",
1085 | "id": "ufNwjr4gSTmx"
1086 | },
1087 | "source": [
1088 | "**Frozenset**: funciona, em linhas gerais, como um conjunto, mas com a diferença de que não pode ser alterado.
\n",
1089 | "Leia mais em: [frozenset](https://www.programiz.com/python-programming/methods/built-in/frozenset)"
1090 | ]
1091 | }
1092 | ],
1093 | "metadata": {
1094 | "colab": {
1095 | "collapsed_sections": [],
1096 | "name": "Conjuntos.ipynb",
1097 | "provenance": [],
1098 | "toc_visible": true,
1099 | "version": "0.3.2"
1100 | },
1101 | "kernelspec": {
1102 | "display_name": "Python 3",
1103 | "language": "python",
1104 | "name": "python3"
1105 | },
1106 | "language_info": {
1107 | "codemirror_mode": {
1108 | "name": "ipython",
1109 | "version": 3
1110 | },
1111 | "file_extension": ".py",
1112 | "mimetype": "text/x-python",
1113 | "name": "python",
1114 | "nbconvert_exporter": "python",
1115 | "pygments_lexer": "ipython3",
1116 | "version": "3.6.8"
1117 | }
1118 | },
1119 | "nbformat": 4,
1120 | "nbformat_minor": 1
1121 | }
1122 |
--------------------------------------------------------------------------------
/notebooks/KdTree.ipynb:
--------------------------------------------------------------------------------
1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"KdTree.ipynb","version":"0.3.2","provenance":[],"collapsed_sections":[],"toc_visible":true},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"5_s1_j_PR5UZ","colab_type":"text"},"cell_type":"markdown","source":["# Introdução"]},{"metadata":{"id":"QzcSWnUKkoxe","colab_type":"text"},"cell_type":"markdown","source":["##KdTree\n"," \n"," \n"," --- \n"," \n"," KdTree, em outras palavras árvore com kd(k-dimensões), é uma estrutura de dados que particiona e organiza pontos em um k-dimensional para responder rapidamente as consultas dos pontos vizinhos mais próximos no espaço. Uma árvore kd genérica pode suportar qualquer número de dimensões e pode retornar o vizinho mais próximo ou um conjunto de N vizinhos mais próximos.\n"," \n"," Os algoritmos mais comuns constroem árvore kds dividindo os conjuntos de pontos. Cada nó na árvore está definido em um plano por uma das dimensões das partições do conjunto de pontos em esquerda/direita, cada um com a metade dos pontos do nó pai. Os filhos são divididos novamente ao meio, usando planos com dimensão diferente.\n","---"]},{"metadata":{"id":"v9IcnmsckjtK","colab_type":"text"},"cell_type":"markdown","source":["#Estrutura"]},{"metadata":{"id":"452d_NF-MZDy","colab_type":"text"},"cell_type":"markdown","source":["### Antes de começarmos o nosso código precisamos incluir as seguintes ferramentas:"]},{"metadata":{"id":"BC3UxDgtmh9E","colab_type":"code","colab":{}},"cell_type":"code","source":["#importando o numpy e transformando em np \n","import numpy as np\n","#vai nos possibilitar de usar a função KdTree\n","from scipy import spatial"],"execution_count":0,"outputs":[]},{"metadata":{"id":"MQ8-lKztVY0p","colab_type":"text"},"cell_type":"markdown","source":["###Construindo uma árvore com duas dimensões:"]},{"metadata":{"id":"ROCLw1vB6gTI","colab_type":"code","colab":{}},"cell_type":"code","source":["import numpy as np\n","from scipy import spatial\n","\n","\n","#Fazer uma matriz variando o indice, ex.: [x:y] vai variar de x ate y-1\n","#A distância desses índices representa a quantidade de linhas e colunas\n","#O primeiro argumento representa as linhas e o segundo as colunas\n","x,y = np.mgrid[5:10,3:6]\n","#print('x: \\n %s \\n y: \\n %s \\n' % (x,y))\n","\n","\n","#Faz uma lista com os pares do zip \n","#Monta as coordenadas com o zip(forma pares dois a dois (coordenadas)) e coloca na lista\n","pontos = list(zip(x.ravel(), y.ravel()))\n","print('os pontos da árvre: \\n %s \\n' % (pontos))\n","\n","\n","#Faz a montagem da árvore(tree)\n","tree = spatial.KDTree(pontos)\n","#imprime todos os pontos\n","print('árvore tree: \\n %s' % (tree.data))\n","\n"],"execution_count":0,"outputs":[]},{"metadata":{"id":"BrluavvIOyuE","colab_type":"text"},"cell_type":"markdown","source":["###Árvore com três:"]},{"metadata":{"id":"8-_mTM6IOz_V","colab_type":"code","colab":{}},"cell_type":"code","source":["x,y,z = np.mgrid[2:5,3:6,1:5]\n","#print('x: \\n %s \\n y: \\n %s \\n z: \\n %s' % (x,y,z))\n","\n","pontos = list(zip(x.ravel(), y.ravel(), z.ravel()))\n","print('os pontos da árvre maokai: \\n %s \\n' % (pontos))\n","maokai = spatial.KDTree(pontos)\n","\n","#print('árvore maokai: \\n %s' % (maokai.data)) #pode usar esse tbm\n","\n","#imprime pontos com os ids\n","i = 0\n","for val in pontos:\n"," print(i,\" (\",val[0],\",\",val[1],\",\",val[2],\")\")\n"," i = i+1\n","#segue o mesmo raciocinio para uma arvorede k-dimencional :)"],"execution_count":0,"outputs":[]},{"metadata":{"id":"CQJETuYzOkus","colab_type":"text"},"cell_type":"markdown","source":["###Funções usadas\n","\n","**np.mgrid**\n","\n"," § Função que cria uma \"malha\" de números a partir do range informado quando chamada, onde a primeira \"malha\" de números terá suas linhas com números iguais e a segunda com as colunas com números iguais.\n","\n","**.ravel()**\n"," \n"," § A função ravel tem o objetivo de pegar os números obitidos pela \"malha\" (np.mgrid) e \"desfia-los\" e \"trasforma-lo num array\".\n","\n","**zip()**\n"," \n"," § No código ele irá junta um valor do x.ravel com um valor do y.ravel para formar pontos.\n","\n","**list()**\n"," \n"," § Faz uma lista com todos os pontos obtidos após a função zip."]},{"metadata":{"id":"9LM-vKkuBkpD","colab_type":"text"},"cell_type":"markdown","source":["#Algumas funcionalidades"]},{"metadata":{"id":"7GrA1m3rB7v6","colab_type":"text"},"cell_type":"markdown","source":["\n"," query_ball_point(ponto, raio)-> encontra o(s) ponto(s) que estão no raio. Retorna ao(s) id(s).\n","\n"," query([ponto(s)]) -> consulta os vizinhos mais próximos. Retorna a (distancia(s), id(s) do(s) ponto(s)).\n","\n","\n"]},{"metadata":{"id":"pQpcB0ZCEk_e","colab_type":"text"},"cell_type":"markdown","source":["###Demonstrações:"]},{"metadata":{"id":"IBxmCa87SsDk","colab_type":"text"},"cell_type":"markdown","source":["**Query_ball_point: **"]},{"metadata":{"id":"9WVo9C-9Mnli","colab_type":"code","colab":{}},"cell_type":"code","source":["import numpy as np\n","from scipy import spatial\n","\n","y,x = np.mgrid[0:5,2:8]\n","pontos = list(zip(x.ravel(), y.ravel()))\n","cruz = spatial.KDTree(pontos)\n","#print('árvore: \\n %s ' % (cruz.data))\n","i = 0\n","print(\"árvore cruz:\")\n","for val in pontos:\n"," print(i,\" (\",val[0],\",\",val[1],\")\")\n"," i = i+1\n","\n","print('ids dos pontos vizinhos: \\n %s' % (cruz.query_ball_point([2,0],1)))\n","\n","# o gráfico com o resultado do query_ball_point\n","listPoint = vore.query_ball_point([2,0],1)\n","\n","x=[]\n","y=[]\n","for ids in listPoint :\n"," x.append(vore.data[ids][0])\n"," y.append(vore.data[ids][1])\n","\n","plt.plot( x,y, 'o', color='#ff00ff') \n","plt.title(\"Grafico Query ball point\")\n","\n","plt.grid(True)\n","plt.xlabel(\"X\")\n","plt.ylabel(\"Y\")\n","print(\"Grafico de Query_ball_point do ponto [2,0]e distancia 1:\\n\")\n","plt.show()"],"execution_count":0,"outputs":[]},{"metadata":{"id":"wojU65FhTUvW","colab_type":"text"},"cell_type":"markdown","source":["**Query:**"]},{"metadata":{"id":"r7VxNlZEM_Lo","colab_type":"code","colab":{}},"cell_type":"code","source":["import numpy as np\n","from scipy import spatial\n","import matplotlib.pyplot as plt\n","\n","y,x = np.mgrid[0:5,1:8]\n","pontos = list(zip(x.ravel(), y.ravel()))\n","arbol = spatial.KDTree(pontos)\n","\n","\n","print(arbol.query([0,1]))\n","\n","#para mostrar os ids e os pontos\n","i = 0\n","for val in pontos:\n"," print(i,\" (\",val[0],\",\",val[1],\")\")\n"," i = i+1\n","\n","#grafico\n","plt.plot( z,w, 'o', color='#ff00ff') # green bolinha4\n","plt.title(\"Grafico Query\")\n","\n","plt.grid(True)\n","plt.xlabel(\"X\")\n","plt.ylabel(\"Y\")\n","plt.show()\n"],"execution_count":0,"outputs":[]},{"metadata":{"id":"6QtSP9wL67Q4","colab_type":"text"},"cell_type":"markdown","source":["# Práticas"]},{"metadata":{"id":"FVUE9QLVCBzO","colab_type":"text"},"cell_type":"markdown","source":[">1.Aproveitando a árvore criada anteriormente, determine os pontos com raio de no máximo 2 do ponto [2, 4], para isso utilize o query_ball_point para os índices e o .data para mostrar os pontos.\n","\n","\n","\n"]},{"metadata":{"id":"VnYZB98yCxQc","colab_type":"code","colab":{}},"cell_type":"code","source":["ejjiej"],"execution_count":0,"outputs":[]},{"metadata":{"id":"r_C6SUx2Cx9W","colab_type":"text"},"cell_type":"markdown","source":["2. Utilizando a função query, me indique o ponto mais próximo de [3, 7] e sua distância até esse ponto."]},{"metadata":{"id":"p5gdAOiJDTNu","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]},{"metadata":{"id":"J03koMpKDXCV","colab_type":"text"},"cell_type":"markdown","source":["3. Encontre os pontos mais próximos do ponto [5, 2] de raio 3."]},{"metadata":{"id":"9uVGSn3VDlRd","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]},{"metadata":{"id":"VXcethYvid0q","colab_type":"text"},"cell_type":"markdown","source":["*Dica : (nome da arvore).(função)*"]},{"metadata":{"id":"BUVcX44gmss4","colab_type":"text"},"cell_type":"markdown","source":["#Exercícios avançados"]},{"metadata":{"id":"RmbVw-Ea7nY6","colab_type":"text"},"cell_type":"markdown","source":["01. Após observar no mapa de seu bairro, joãozinho percebe que os locais das casas de seus amigos podem ser representados por uma árvore de duas dimensões com linhas e colunas variando de 0:5. Crie para joãozinho uma árvore com essas características mostrando seus pontos e o gráfico formado."]},{"metadata":{"id":"LRs-ZBqV8GsG","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]},{"metadata":{"id":"lFJQ8XQm8H21","colab_type":"text"},"cell_type":"markdown","source":["02. Apos visualizar o gráfico, joãozinho percebe que sua casa esta localizada no ponto de índice 4. Animado pela sua descoberta, ele decide visitar seu amigos mais próximos (com distância de 1). Mostre para joãozinho as opções de pontos que ele tem com essa distância."]},{"metadata":{"id":"ioT0glrg8mYW","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]},{"metadata":{"id":"sqDQ4XJg8nFb","colab_type":"text"},"cell_type":"markdown","source":["3. Joãozinho e amigos querem ir para uma festa e planejam voltar todos para casa mais próxima para dormir. Para saber qual a melhor casa, joãozinho percebe que mapeando a cidade a festa se localizaria no ponto [16,9]. Determine para ele, qual as melhores casas e a distância dela para a festa. "]},{"metadata":{"id":"L9hLwIS686I_","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]},{"metadata":{"id":"1YGF8Cz-N91B","colab_type":"text"},"cell_type":"markdown","source":["4. Joãozinho, malandramente, percebe que as casas com índices impares são de amigos que moram no primeiro andar. Para isso joãozinho decide criar uma árvore com 3 dimensões seguindo os mesmo parâmetros da anterior, só que para as casas pares denomina o eixo z = 0 e para as impares (primeiro andar) z = 1. Crie essa árvore de 3 dimensões para joãozinho."]},{"metadata":{"id":"i_nrMLqqA_0F","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]}]}
--------------------------------------------------------------------------------
/notebooks/LifoQueue.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "name": "Pilhas-Python.ipynb",
7 | "version": "0.3.2",
8 | "provenance": [],
9 | "collapsed_sections": [],
10 | "toc_visible": true,
11 | "include_colab_link": true
12 | },
13 | "kernelspec": {
14 | "name": "python3",
15 | "display_name": "Python 3"
16 | }
17 | },
18 | "cells": [
19 | {
20 | "cell_type": "markdown",
21 | "metadata": {
22 | "id": "view-in-github",
23 | "colab_type": "text"
24 | },
25 | "source": [
26 | "
"
27 | ]
28 | },
29 | {
30 | "metadata": {
31 | "id": "2WrGReSHNepQ",
32 | "colab_type": "text"
33 | },
34 | "cell_type": "markdown",
35 | "source": [
36 | "# Pilhas: conceitos iniciais"
37 | ]
38 | },
39 | {
40 | "metadata": {
41 | "id": "z2JdSK3GJY00",
42 | "colab_type": "text"
43 | },
44 | "cell_type": "markdown",
45 | "source": [
46 | "Uma **pilha** é um tipo de dado abstrato muito utilizado em computação. Seu nome é devido a analogia do comportamento dessa estrutura com uma pilhas de objetos no mundo real. \n",
47 | "\n",
48 | "Considere, por exemplo, uma pilha de cartas, onde uma nova carta adicionada é **sempre adicionada ao topo da pilha**, e qualquer carta que venha a ser retirada é **sempre retirada do topo da pilha**.\n",
49 | "\n",
50 | "Dessa forma, podemos pensar em uma pilha como uma lista dinâmica em que as** operações são realizadas sempre no topo** (na mesma extremidade).\n",
51 | "\n",
52 | "Portanto, em uma estrutura do tipo pilha, o **último elemento inserido é o primeiro a ser removido** ou consultado. Essa estrutura também é conhecida como** LIFO**, do inglês last-in first-out.\n"
53 | ]
54 | },
55 | {
56 | "metadata": {
57 | "id": "iF3ODX8eFEDt",
58 | "colab_type": "text"
59 | },
60 | "cell_type": "markdown",
61 | "source": [
62 | "# Pilhas em Python\n"
63 | ]
64 | },
65 | {
66 | "metadata": {
67 | "id": "S954EGRXGIbW",
68 | "colab_type": "text"
69 | },
70 | "cell_type": "markdown",
71 | "source": [
72 | "##Pilhas Usando listas"
73 | ]
74 | },
75 | {
76 | "metadata": {
77 | "id": "iGD5XQYLl_zA",
78 | "colab_type": "text"
79 | },
80 | "cell_type": "markdown",
81 | "source": [
82 | "\n",
83 | "No Python podemos implementar uma pilha de forma rudimentar usando uma lista, pois essa estrutura de dados nos oferece métodos para que possamos realizar as operações necessárias na nossa pilha.\n",
84 | "\n",
85 | "Os seguintes métodos serão uteis na implementação de pilhas em Python:\n",
86 | "\n",
87 | "\n",
88 | "* list.**append(x)** : adicina um item no final da lista, onde x = item a ser adicionado.\n",
89 | "* list.**pop()**: remove um item do final da lista.\n",
90 | "* list**[-1]**: acessa o item que esta no final da lista(topo da pilha).\n",
91 | "* **len(lista)**: retorna o tamanho atual da lista. "
92 | ]
93 | },
94 | {
95 | "metadata": {
96 | "id": "jtAHjoXyJeIq",
97 | "colab_type": "text"
98 | },
99 | "cell_type": "markdown",
100 | "source": [
101 | "Criando e adicionando itens a pilha."
102 | ]
103 | },
104 | {
105 | "metadata": {
106 | "id": "vRZHq3GTGmPh",
107 | "colab_type": "code",
108 | "outputId": "4c10e549-4e51-46f6-9905-5fb0ed177ee7",
109 | "colab": {
110 | "base_uri": "https://localhost:8080/",
111 | "height": 34
112 | }
113 | },
114 | "cell_type": "code",
115 | "source": [
116 | "pilha = [] #criando uma lista/pilha vazia.\n",
117 | "pilha.append(1) #adiciona um item no final da lista/topo da pilha\n",
118 | "pilha.append(2) #adiciona um item no final da lista/topo da pilha\n",
119 | "print(pilha)"
120 | ],
121 | "execution_count": 0,
122 | "outputs": [
123 | {
124 | "output_type": "stream",
125 | "text": [
126 | "[1, 2]\n"
127 | ],
128 | "name": "stdout"
129 | }
130 | ]
131 | },
132 | {
133 | "metadata": {
134 | "id": "qsAYb1rpJlA1",
135 | "colab_type": "text"
136 | },
137 | "cell_type": "markdown",
138 | "source": [
139 | "Removendo itens do topo da pilha."
140 | ]
141 | },
142 | {
143 | "metadata": {
144 | "id": "vTi4vXoZJr9L",
145 | "colab_type": "code",
146 | "outputId": "bdc37390-8714-4b3a-c584-e61e6a318842",
147 | "colab": {
148 | "base_uri": "https://localhost:8080/",
149 | "height": 51
150 | }
151 | },
152 | "cell_type": "code",
153 | "source": [
154 | "print(\"Pilha antes da remoção: \", pilha)\n",
155 | "pilha.pop() #removendo item do topo da pilha\n",
156 | "print(\"Pilha depois da remoção: \", pilha)"
157 | ],
158 | "execution_count": 0,
159 | "outputs": [
160 | {
161 | "output_type": "stream",
162 | "text": [
163 | "Pilha antes da remoção: [1, 2]\n",
164 | "Pilha depois da remoção: [1]\n"
165 | ],
166 | "name": "stdout"
167 | }
168 | ]
169 | },
170 | {
171 | "metadata": {
172 | "id": "1Kuxen25KfF7",
173 | "colab_type": "text"
174 | },
175 | "cell_type": "markdown",
176 | "source": [
177 | "Acessando o item que esta no topo da pilha."
178 | ]
179 | },
180 | {
181 | "metadata": {
182 | "id": "Phfee2J7KmH6",
183 | "colab_type": "code",
184 | "outputId": "5f5bf730-8920-441b-9591-e8b0740c283d",
185 | "colab": {
186 | "base_uri": "https://localhost:8080/",
187 | "height": 34
188 | }
189 | },
190 | "cell_type": "code",
191 | "source": [
192 | "pilha.append(3)\n",
193 | "print(pilha[-1])#Acessando o item do topo da pilha"
194 | ],
195 | "execution_count": 0,
196 | "outputs": [
197 | {
198 | "output_type": "stream",
199 | "text": [
200 | "3\n"
201 | ],
202 | "name": "stdout"
203 | }
204 | ]
205 | },
206 | {
207 | "metadata": {
208 | "id": "5LbB9fazKwg9",
209 | "colab_type": "text"
210 | },
211 | "cell_type": "markdown",
212 | "source": [
213 | "Verificando o tamanho da pilha. "
214 | ]
215 | },
216 | {
217 | "metadata": {
218 | "id": "5-rUaLCiK3Pk",
219 | "colab_type": "code",
220 | "outputId": "6b2b32f7-039b-4645-a37b-078d0bd16bd6",
221 | "colab": {
222 | "base_uri": "https://localhost:8080/",
223 | "height": 34
224 | }
225 | },
226 | "cell_type": "code",
227 | "source": [
228 | "print(len(pilha))"
229 | ],
230 | "execution_count": 0,
231 | "outputs": [
232 | {
233 | "output_type": "stream",
234 | "text": [
235 | "2\n"
236 | ],
237 | "name": "stdout"
238 | }
239 | ]
240 | },
241 | {
242 | "metadata": {
243 | "id": "QLGwGbgwK-eq",
244 | "colab_type": "text"
245 | },
246 | "cell_type": "markdown",
247 | "source": [
248 | "**Dica**: Sempre é bom verificar o tamanho da pilha antes de remover um item dela."
249 | ]
250 | },
251 | {
252 | "metadata": {
253 | "id": "pOknPfvEZfpo",
254 | "colab_type": "text"
255 | },
256 | "cell_type": "markdown",
257 | "source": [
258 | "###Exercicios de Fixação"
259 | ]
260 | },
261 | {
262 | "metadata": {
263 | "id": "yOT_8YXuPQtC",
264 | "colab_type": "text"
265 | },
266 | "cell_type": "markdown",
267 | "source": [
268 | "1 - Elabore um programa e as TADs necessárias, sem usar pilha, que simule uma\n",
269 | "sequência de operações Empilha (push) e Desempilha (pop), e determine se está\n",
270 | "ocorrendo um underflow (tentativa de Desempilhar em uma pilha vazia) ou não em\n",
271 | "alguma operação Desempilha. "
272 | ]
273 | },
274 | {
275 | "metadata": {
276 | "id": "J4BPWz_4ZqMd",
277 | "colab_type": "code",
278 | "colab": {}
279 | },
280 | "cell_type": "code",
281 | "source": [
282 | ""
283 | ],
284 | "execution_count": 0,
285 | "outputs": []
286 | },
287 | {
288 | "metadata": {
289 | "id": "EdT02YrLmw57",
290 | "colab_type": "text"
291 | },
292 | "cell_type": "markdown",
293 | "source": [
294 | "2 - Utilizando os métodos append() e pop() de listas, escreva uma função bem_formada() que recebe um string s contendo apenas os caracteres **(,** **)**, **[**, **]**, devolve True caso a expressão estiver bem formada e False caso contrário."
295 | ]
296 | },
297 | {
298 | "metadata": {
299 | "id": "GZAOHDcLZq09",
300 | "colab_type": "code",
301 | "colab": {}
302 | },
303 | "cell_type": "code",
304 | "source": [
305 | ""
306 | ],
307 | "execution_count": 0,
308 | "outputs": []
309 | },
310 | {
311 | "metadata": {
312 | "id": "sE9BVulIGa5p",
313 | "colab_type": "text"
314 | },
315 | "cell_type": "markdown",
316 | "source": [
317 | "##Usando Queue.py"
318 | ]
319 | },
320 | {
321 | "metadata": {
322 | "id": "byXUiit_Ga4H",
323 | "colab_type": "text"
324 | },
325 | "cell_type": "markdown",
326 | "source": [
327 | ""
328 | ]
329 | },
330 | {
331 | "metadata": {
332 | "id": "85A7w1isnrHc",
333 | "colab_type": "text"
334 | },
335 | "cell_type": "markdown",
336 | "source": [
337 | "Uma maneira mais segura de implementar uma pilha é usando a classe queue.LifoQueue da library queue.py. Os metodos a abaixo serão utilizados na manipilação e verificação da pilha.\n",
338 | "\n",
339 | "* **Queue.qsize()**: retorna o tamanho da pilha.\n",
340 | "* **Queue.empty()**: retorna True(verdadeiro) se a pilha estiver vazia, False(falso) caso contrario.\n",
341 | "* **Queue.full()**: returna True(verdadeiro) se a pilha estiver cheia, False(falso) caso contrario.\n",
342 | "* **Queue.put(item)**: coloca um item na pilha(topo).\n",
343 | "* **Queue.get()**: remove e retorna o item que esta no topo da pilha.\n",
344 | "\n",
345 | "Onde, Queue = nome da pilha."
346 | ]
347 | },
348 | {
349 | "metadata": {
350 | "id": "mNpFsAhgquTZ",
351 | "colab_type": "text"
352 | },
353 | "cell_type": "markdown",
354 | "source": [
355 | "No código abaixo criamos uma variavel do tipo queue.LifoQueue."
356 | ]
357 | },
358 | {
359 | "metadata": {
360 | "id": "0F6D0TFGq-ij",
361 | "colab_type": "code",
362 | "colab": {}
363 | },
364 | "cell_type": "code",
365 | "source": [
366 | "from queue import LifoQueue\n",
367 | "pilha = LifoQueue()"
368 | ],
369 | "execution_count": 0,
370 | "outputs": []
371 | },
372 | {
373 | "metadata": {
374 | "id": "SlpVetlsroGP",
375 | "colab_type": "text"
376 | },
377 | "cell_type": "markdown",
378 | "source": [
379 | "Verificando se a pilha esta vazia."
380 | ]
381 | },
382 | {
383 | "metadata": {
384 | "id": "DKeyjoyMr0K0",
385 | "colab_type": "code",
386 | "outputId": "fd403779-1142-464c-8da9-c9dd817e737f",
387 | "colab": {
388 | "base_uri": "https://localhost:8080/",
389 | "height": 34
390 | }
391 | },
392 | "cell_type": "code",
393 | "source": [
394 | "print(pilha.empty())"
395 | ],
396 | "execution_count": 0,
397 | "outputs": [
398 | {
399 | "output_type": "stream",
400 | "text": [
401 | "True\n"
402 | ],
403 | "name": "stdout"
404 | }
405 | ]
406 | },
407 | {
408 | "metadata": {
409 | "id": "WmLlS_-RsAA0",
410 | "colab_type": "text"
411 | },
412 | "cell_type": "markdown",
413 | "source": [
414 | "Adicionado um item ao topo da pilha."
415 | ]
416 | },
417 | {
418 | "metadata": {
419 | "id": "iJRCftG_sEgH",
420 | "colab_type": "code",
421 | "colab": {}
422 | },
423 | "cell_type": "code",
424 | "source": [
425 | "pilha.put(\"teste\")"
426 | ],
427 | "execution_count": 0,
428 | "outputs": []
429 | },
430 | {
431 | "metadata": {
432 | "id": "MEOr9rH8spgY",
433 | "colab_type": "text"
434 | },
435 | "cell_type": "markdown",
436 | "source": [
437 | "Agora vamos verificar se a pilha esta vazia, depois o usar o metodo get para remover e retornar o item que esta no topo da pilha e verificar se ela esta vazia novamente."
438 | ]
439 | },
440 | {
441 | "metadata": {
442 | "id": "XNq-29ICs6QQ",
443 | "colab_type": "code",
444 | "outputId": "9938be82-2d30-4f03-deeb-531509e69488",
445 | "colab": {
446 | "base_uri": "https://localhost:8080/",
447 | "height": 68
448 | }
449 | },
450 | "cell_type": "code",
451 | "source": [
452 | "print(pilha.empty())\n",
453 | "print(pilha.get())\n",
454 | "print(pilha.empty())"
455 | ],
456 | "execution_count": 0,
457 | "outputs": [
458 | {
459 | "output_type": "stream",
460 | "text": [
461 | "False\n",
462 | "teste\n",
463 | "True\n"
464 | ],
465 | "name": "stdout"
466 | }
467 | ]
468 | },
469 | {
470 | "metadata": {
471 | "id": "9p9I8NtPudLy",
472 | "colab_type": "text"
473 | },
474 | "cell_type": "markdown",
475 | "source": [
476 | "**OBS**: não utilize o metodo **get** em uma pilha vazia."
477 | ]
478 | },
479 | {
480 | "metadata": {
481 | "id": "WLFrNphluwqq",
482 | "colab_type": "text"
483 | },
484 | "cell_type": "markdown",
485 | "source": [
486 | "Por fim, adicionamos itens a pilha e verificamos o seu tamanho a cada adição."
487 | ]
488 | },
489 | {
490 | "metadata": {
491 | "id": "IDVKpFAvu8De",
492 | "colab_type": "code",
493 | "outputId": "cad30672-df52-44ca-f18d-ce9d2ffc324f",
494 | "colab": {
495 | "base_uri": "https://localhost:8080/",
496 | "height": 68
497 | }
498 | },
499 | "cell_type": "code",
500 | "source": [
501 | "pilha.put(\"teste1\")\n",
502 | "print(pilha.qsize())\n",
503 | "pilha.put(\"teste2\")\n",
504 | "print(pilha.qsize())\n",
505 | "pilha.put(\"teste3\")\n",
506 | "print(pilha.qsize())"
507 | ],
508 | "execution_count": 0,
509 | "outputs": [
510 | {
511 | "output_type": "stream",
512 | "text": [
513 | "1\n",
514 | "2\n",
515 | "3\n"
516 | ],
517 | "name": "stdout"
518 | }
519 | ]
520 | },
521 | {
522 | "metadata": {
523 | "id": "QG_Asqm4Iojs",
524 | "colab_type": "text"
525 | },
526 | "cell_type": "markdown",
527 | "source": [
528 | "###Exercicios de Fixação"
529 | ]
530 | },
531 | {
532 | "metadata": {
533 | "id": "d9uh5po7KWS7",
534 | "colab_type": "text"
535 | },
536 | "cell_type": "markdown",
537 | "source": [
538 | "1 - Crie uma função que receba um número n e armazene todos os resultados da operação fatoria de 1 até n em um pilha usando a classe queue.LifoQueue.\n",
539 | "\n",
540 | "Exemplo:\n",
541 | "* Valor de n: 4\n",
542 | "* Valores armazendos: 1! , 2! , 3! , 4!\n",
543 | "\n",
544 | "**Sugestão:** Usar o Queue.get() e imprimir os valores "
545 | ]
546 | },
547 | {
548 | "metadata": {
549 | "id": "RMa7MTrNJQGn",
550 | "colab_type": "code",
551 | "colab": {}
552 | },
553 | "cell_type": "code",
554 | "source": [
555 | ""
556 | ],
557 | "execution_count": 0,
558 | "outputs": []
559 | },
560 | {
561 | "metadata": {
562 | "id": "jakEF9ztMl3Z",
563 | "colab_type": "text"
564 | },
565 | "cell_type": "markdown",
566 | "source": [
567 | "2 - Use as operações/funções Empilha (push), Desempilha (pop) e Vazia (Empty) para construir operações que façam o seguinte:\n",
568 | "\n",
569 | "* Dado um inteiro n, definir o item i como o n-ésimo elemento a partir do topo da pilha, deixando a pilha sem seus n elementos superiores (obs: no final, o item i será o topo da pilha).\n",
570 | "* Dado um inteiro n, definir o item i como o n-ésimo elemento a partir do topo da pilha, deixando a pilha inalterada.\n",
571 | "* Dado um item i, deixar a pilha somente com o item i."
572 | ]
573 | },
574 | {
575 | "metadata": {
576 | "id": "0HqfZcuWPRfT",
577 | "colab_type": "code",
578 | "colab": {}
579 | },
580 | "cell_type": "code",
581 | "source": [
582 | ""
583 | ],
584 | "execution_count": 0,
585 | "outputs": []
586 | },
587 | {
588 | "metadata": {
589 | "id": "Atdthd1tjZ1b",
590 | "colab_type": "text"
591 | },
592 | "cell_type": "markdown",
593 | "source": [
594 | "# Importância e usos gerais\n",
595 | "\n",
596 | "Como as pilhas utilizam bibliotecas de outros tipos de dados abstratos, como as **listas** e também sua própria biblioteca **lifoQueue()**, podemos dizer que elas (as pilhas), servem para abstrair certos tipos de problemas da realidade. "
597 | ]
598 | },
599 | {
600 | "metadata": {
601 | "id": "EyCho6tzjZmr",
602 | "colab_type": "text"
603 | },
604 | "cell_type": "markdown",
605 | "source": [
606 | "## Chamadas de função\n",
607 | "Talvez a mais famosa utilização de pilhas em computação esteja no gerenciamento de chamadas de função de um programa. Uma pilha pode ser usada para manter informações sobre as funções de um programa que estejam ativas, aguardando por serem terminadas. Considere o seguinte exemplo:"
608 | ]
609 | },
610 | {
611 | "metadata": {
612 | "id": "h20mAuaEklND",
613 | "colab_type": "code",
614 | "colab": {}
615 | },
616 | "cell_type": "code",
617 | "source": [
618 | "def ola():\n",
619 | " print(\"olá, \")\n",
620 | " mundo()\n",
621 | " \n",
622 | "def mundo():\n",
623 | " print(\"mundo!\")\n",
624 | " \n",
625 | "def olamundo():\n",
626 | " ola()\n",
627 | " \n",
628 | "olamundo()"
629 | ],
630 | "execution_count": 0,
631 | "outputs": []
632 | },
633 | {
634 | "metadata": {
635 | "id": "0WlZ-DrNk4Vz",
636 | "colab_type": "text"
637 | },
638 | "cell_type": "markdown",
639 | "source": [
640 | "A primeira função a ser chamada é a olamundo(), que por sua vez chama a função ola(), então a função olamundo() é empilhada, pois seu término depende do término da função ola(). \n",
641 | "\n",
642 | "Essa, por sua vez, chama a função mundo() e é empilhada. Ao terminar a execução da função mundo(), a função ola() é desempilhada e sua execução termina de onde havia parado (chamada à função mundo()). \n",
643 | "\n",
644 | "Como não há mais nada a ser executado nessa função, sua execução termina, e a função olamundo()é desempilhada e sua execução continua, encerrando assim o programa."
645 | ]
646 | },
647 | {
648 | "metadata": {
649 | "id": "lySiRm1bl6xb",
650 | "colab_type": "text"
651 | },
652 | "cell_type": "markdown",
653 | "source": [
654 | "## Checagem de parênteses \n",
655 | "Outra utilização de pilhas é a verificação do balanceamento de parênteses. Como saber se os seguintes parênteses estão balanceados, isto é, se para cada abre-parênteses, existe um fecha-parênteses correspondente?\n",
656 | "\n",
657 | "(((((((((((((((((()()()()))))))())))()))()))()))((()))))\n",
658 | "\n",
659 | "Uma forma bem simples de resolver esse problema é ler a sequência de parênteses, um por um e, a cada abre-parênteses que encontrarmos, vamos empilhá-lo. \n",
660 | "\n",
661 | "Quando encontrarmos um fecha-parênteses, devemos desempilhar um abre-parênteses, pois encontramos um fecha-parênteses correspondente a ele. \n",
662 | "\n",
663 | "Assim, ao final da avaliação da sequência acima, se ela estiver balanceada corretamente, não restarão elementos na pilha."
664 | ]
665 | },
666 | {
667 | "metadata": {
668 | "id": "PS2DgbYZ_r4R",
669 | "colab_type": "text"
670 | },
671 | "cell_type": "markdown",
672 | "source": [
673 | "# Exercicios"
674 | ]
675 | },
676 | {
677 | "metadata": {
678 | "id": "2Z49BLX9AGn-",
679 | "colab_type": "text"
680 | },
681 | "cell_type": "markdown",
682 | "source": [
683 | "1 - Utilizando uma pilha, escreva uma progama que recebe um número interio positivo e converte para binário puro.\n",
684 | "\n",
685 | "Exemplos:\n",
686 | "\n",
687 | "5 → 101\n",
688 | "\n",
689 | "13 → 1101\n",
690 | "\n",
691 | "1 → 1"
692 | ]
693 | },
694 | {
695 | "metadata": {
696 | "id": "EXEeuc0sxgKr",
697 | "colab_type": "text"
698 | },
699 | "cell_type": "markdown",
700 | "source": [
701 | "Resolução:"
702 | ]
703 | },
704 | {
705 | "metadata": {
706 | "id": "Ui0VbK3BuTMY",
707 | "colab_type": "code",
708 | "outputId": "4ce3a316-67fe-4c0f-807a-94ac51be1924",
709 | "colab": {
710 | "base_uri": "https://localhost:8080/",
711 | "height": 51
712 | }
713 | },
714 | "cell_type": "code",
715 | "source": [
716 | "import queue\n",
717 | "\n",
718 | "binario = queue.LifoQueue()\n",
719 | "n = int(input(\"Digite um número inteiro: \"))\n",
720 | "print(\"O número {} em binario:\".format(n), end=\" \")\n",
721 | "\n",
722 | "while n >= 2:\n",
723 | " binario.put(n % 2)\n",
724 | " n = n // 2\n",
725 | "binario.put(1)\n",
726 | "\n",
727 | "while not binario.empty():\n",
728 | " print(binario.get(), end=\"\")"
729 | ],
730 | "execution_count": 0,
731 | "outputs": [
732 | {
733 | "output_type": "stream",
734 | "text": [
735 | "Digite um número inteiro: 13\n",
736 | "O número 13 em binario: 1101"
737 | ],
738 | "name": "stdout"
739 | }
740 | ]
741 | },
742 | {
743 | "metadata": {
744 | "id": "bsER7jm7zLdc",
745 | "colab_type": "text"
746 | },
747 | "cell_type": "markdown",
748 | "source": [
749 | "2 - Utilizando as operações de manipulação de pilhas vistas em sala, uma pilha auxiliar e\n",
750 | "uma variável do tipo TipoItem, escreva um procedimento que remove um item com\n",
751 | "chave c de uma posição qualquer de uma pilha. \n",
752 | "\n",
753 | "Note que você não tem acesso à\n",
754 | "estrutura interna da pilha (topo, item, etc), apenas às operações de manipulação."
755 | ]
756 | },
757 | {
758 | "metadata": {
759 | "id": "CTAYFr7xzLAR",
760 | "colab_type": "code",
761 | "colab": {}
762 | },
763 | "cell_type": "code",
764 | "source": [
765 | ""
766 | ],
767 | "execution_count": 0,
768 | "outputs": []
769 | },
770 | {
771 | "metadata": {
772 | "id": "zK7wL76rDBiZ",
773 | "colab_type": "text"
774 | },
775 | "cell_type": "markdown",
776 | "source": [
777 | "3 - Considere que um editor de texto representa os caracteres digitados como uma\n",
778 | "pilha, sendo que o último caracter lido fica no topo\n",
779 | "\n",
780 | "* Alguns comandos apagam caracteres. Por exemplo, o backspace apaga o último caractere\n",
781 | "lido\n",
782 | "\n",
783 | "* Alguns comandos apagam tudo o que já foi lido anteriormente\n",
784 | "\n",
785 | "* Considere que, no seu editor, # representa backspacee @ indica “apagar tudo”\n",
786 | "\n",
787 | "* Faça um programa que execute essas ações usando o TAD pilha"
788 | ]
789 | },
790 | {
791 | "metadata": {
792 | "id": "ZU2TqJq0DOrN",
793 | "colab_type": "code",
794 | "colab": {}
795 | },
796 | "cell_type": "code",
797 | "source": [
798 | ""
799 | ],
800 | "execution_count": 0,
801 | "outputs": []
802 | },
803 | {
804 | "metadata": {
805 | "id": "5yKsy4b7DQtI",
806 | "colab_type": "text"
807 | },
808 | "cell_type": "markdown",
809 | "source": [
810 | "4 - Às vezes, na aritmética tradicional, faz-se necessário usar parênteses para dar o significado\n",
811 | "correto à expressão. Por exemplo\n",
812 | "\n",
813 | "* A*B-C/D equivale a: (A*B)-(C/D)\n",
814 | "\n",
815 | "\n",
816 | "Na notação polonesa reversa (posfixa), os operadores aparecem depois dos operandos e dispensa parênteses\n",
817 | " \n",
818 | " * Exemplo: AB*CD/-\n",
819 | "\n",
820 | "Interpretação da notação posfixa usando pilha:\n",
821 | "\n",
822 | "* Empilha operandos até encontrar um operador;\n",
823 | "* Retira os operandos, calcula e empilha o resultado;\n",
824 | "* Até que se chegue ao final da expressão.\n",
825 | "\n",
826 | "Implemente uma função que calcule o valor de uma expressão posfixa passada\n",
827 | "por parâmetro utilizando uma pilha"
828 | ]
829 | },
830 | {
831 | "metadata": {
832 | "id": "v6WJUB2rE7SN",
833 | "colab_type": "code",
834 | "colab": {}
835 | },
836 | "cell_type": "code",
837 | "source": [
838 | ""
839 | ],
840 | "execution_count": 0,
841 | "outputs": []
842 | }
843 | ]
844 | }
--------------------------------------------------------------------------------
/notebooks/Queue-deque.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "colab_type": "text",
7 | "id": "5LZAAs_ThZah"
8 | },
9 | "source": [
10 | "# Fila"
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "metadata": {
16 | "colab_type": "text",
17 | "id": "dbnA8HEKh_24"
18 | },
19 | "source": [
20 | "Neste primeiro tópico, iremos aprender um pouco sobre a estrutura de dados fila (do inglês queue). \n",
21 | "\n",
22 | "Para exemplificar, podemos assimilar seu conceito a uma ação muito comum do nosso cotidiano. \n",
23 | "\n",
24 | "Considere que você precisará de um atendimento presencial em um banco, no qual muitas vezes é necessário entrar em uma fila. Nessas filas, a primeira pessoa a chegar receberá prioridade máxima no atendimento, do mesmo modo que a última pessoa a chegar terá a menor prioridade. \n",
25 | "\n",
26 | "O TAD fila se comporta de forma similar. Logo, o primeiro elemento adicionado na fila será o primeiro a ser processado. Além disso, sempre que um novo elemento é adicionado, este será inserido no final da fila, e sempre que um elemento for removido, remove-se do início. \n",
27 | "\n",
28 | "> Esse princípio é conhecido como **FIFO** (do inglês first-in first-out)."
29 | ]
30 | },
31 | {
32 | "cell_type": "markdown",
33 | "metadata": {
34 | "colab_type": "text",
35 | "id": "fXANuXEEm_9v"
36 | },
37 | "source": [
38 | ""
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {
44 | "colab_type": "text",
45 | "id": "ij8o_T_jniNk"
46 | },
47 | "source": [
48 | "Para fins de aplicação, podemos listar exemplos de fila em um sistema, como o controle de documentos para impressão ou a troca de mensagens entre computadores numa rede. \n",
49 | "\n",
50 | "É importante destacar que, no Python, esse TAD foi construído para ser usado principalmente em aplicações com programação paralela. "
51 | ]
52 | },
53 | {
54 | "cell_type": "markdown",
55 | "metadata": {
56 | "colab_type": "text",
57 | "id": "xYZVcNGZnmOI"
58 | },
59 | "source": [
60 | "> Programação paralela é utilizada para executar mais de uma instrução ao mesmo tempo. O seu principal benefício é a resposta em uma menor duração, já que os problemas são divididos em partes que serão resolvidas utilizando múltiplos núcleos de processamento.\n",
61 | "\n"
62 | ]
63 | },
64 | {
65 | "cell_type": "markdown",
66 | "metadata": {
67 | "colab_type": "text",
68 | "id": "sXJfOiFBPUyu"
69 | },
70 | "source": [
71 | "No Python, podemos utilizar a classe `Queue` da biblioteca `queue` para a implementação de filas.\n"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "execution_count": 1,
77 | "metadata": {
78 | "colab": {},
79 | "colab_type": "code",
80 | "id": "mroJvUeaPdEn"
81 | },
82 | "outputs": [],
83 | "source": [
84 | "from queue import Queue\n",
85 | "fila = Queue(maxsize=5)"
86 | ]
87 | },
88 | {
89 | "cell_type": "markdown",
90 | "metadata": {
91 | "colab_type": "text",
92 | "id": "-Hp7QitjP8p3"
93 | },
94 | "source": [
95 | "> `maxsize` é um inteiro que define a quantidade máxima de elementos que podem ser adicionados à fila. Se for menor ou igual a zero, a fila terá um tamanho ilimitado."
96 | ]
97 | },
98 | {
99 | "cell_type": "markdown",
100 | "metadata": {
101 | "colab_type": "text",
102 | "id": "0lCkd90CRskA"
103 | },
104 | "source": [
105 | "Agora, se quisermos adicionar elementos à fila, utilizamos o método `put()`."
106 | ]
107 | },
108 | {
109 | "cell_type": "code",
110 | "execution_count": 0,
111 | "metadata": {
112 | "colab": {},
113 | "colab_type": "code",
114 | "id": "r2FousAARyKy"
115 | },
116 | "outputs": [],
117 | "source": [
118 | "fila.put(1)\n",
119 | "fila.put(2)\n",
120 | "fila.put(3)\n",
121 | "fila.put(4)\n",
122 | "fila.put(5)"
123 | ]
124 | },
125 | {
126 | "cell_type": "markdown",
127 | "metadata": {
128 | "colab_type": "text",
129 | "id": "VIcEFxPFoQl0"
130 | },
131 | "source": [
132 | "O método qsize() retorna a quantidade de elementos que existem na fila.\n"
133 | ]
134 | },
135 | {
136 | "cell_type": "code",
137 | "execution_count": 0,
138 | "metadata": {
139 | "colab": {},
140 | "colab_type": "code",
141 | "id": "aJyUquQdoTyl"
142 | },
143 | "outputs": [],
144 | "source": [
145 | "print(fila.qsize())"
146 | ]
147 | },
148 | {
149 | "cell_type": "markdown",
150 | "metadata": {
151 | "colab_type": "text",
152 | "id": "4JPUIwzDohSJ"
153 | },
154 | "source": [
155 | "Para verificar se a fila está cheia, utilizamos o método `full()`."
156 | ]
157 | },
158 | {
159 | "cell_type": "code",
160 | "execution_count": 0,
161 | "metadata": {
162 | "colab": {},
163 | "colab_type": "code",
164 | "id": "g48SI_PsopPT"
165 | },
166 | "outputs": [],
167 | "source": [
168 | "print(fila.full())"
169 | ]
170 | },
171 | {
172 | "cell_type": "markdown",
173 | "metadata": {
174 | "colab_type": "text",
175 | "id": "JpoRs5GFox_w"
176 | },
177 | "source": [
178 | "Note que, como a fila já está cheia, se tentássemos adicionar um novo elemento à ela, deveria não adicioná-lo ou resultar em algum erro. \n",
179 | "\n",
180 | "Porém, como a `Queue` do Python é um TAD construído para ser usado principalmente em aplicações de programação paralela, o novo elemento irá para uma espécie de “fila de espera”. \n",
181 | "\n",
182 | "Isto significa que este terá que aguardar outro elemento já existente na fila ser processado e removido para que só então possa ser adicionado à fila. \n",
183 | "\n",
184 | "Contudo, se utilizarmos o parâmetro `block` do método `put()`, podemos controlar a entrada de dados na fila. \n",
185 | "\n",
186 | "Ao configurar `block` como `False`, o método `put()` irá tentar adicionar o elemento e, se a fila estiver cheia, irá resultar na exceção `Full`. "
187 | ]
188 | },
189 | {
190 | "cell_type": "code",
191 | "execution_count": 0,
192 | "metadata": {
193 | "colab": {},
194 | "colab_type": "code",
195 | "id": "td9B9_MfoxnP"
196 | },
197 | "outputs": [],
198 | "source": [
199 | "fila.put(6, block=False)"
200 | ]
201 | },
202 | {
203 | "cell_type": "markdown",
204 | "metadata": {
205 | "colab_type": "text",
206 | "id": "UC7rnUhtpE26"
207 | },
208 | "source": [
209 | "De maneira análoga a lógica anterior, podemos também utilizar o método `put_nowait()`, que é similar ao `put()` com o parâmetro `block` definido como `False`."
210 | ]
211 | },
212 | {
213 | "cell_type": "code",
214 | "execution_count": 0,
215 | "metadata": {
216 | "colab": {},
217 | "colab_type": "code",
218 | "id": "hobGf7SroshX"
219 | },
220 | "outputs": [],
221 | "source": [
222 | "fila.put_nowait(6)"
223 | ]
224 | },
225 | {
226 | "cell_type": "markdown",
227 | "metadata": {
228 | "colab_type": "text",
229 | "id": "0inz0r2wpTyF"
230 | },
231 | "source": [
232 | "O método `get()` retorna e remove o primeiro elemento da fila, ou seja, aquele que foi adicionado antes de todos os outros."
233 | ]
234 | },
235 | {
236 | "cell_type": "code",
237 | "execution_count": 0,
238 | "metadata": {
239 | "colab": {},
240 | "colab_type": "code",
241 | "id": "wjL2U5KmpgOc"
242 | },
243 | "outputs": [],
244 | "source": [
245 | "while not fila.empty():\n",
246 | " elemento = fila.get()\n",
247 | " print(elemento)"
248 | ]
249 | },
250 | {
251 | "cell_type": "markdown",
252 | "metadata": {
253 | "colab_type": "text",
254 | "id": "xiww3OP7pjjs"
255 | },
256 | "source": [
257 | "Para verificar se uma lista está vazia, utilizamos o método `empty()`."
258 | ]
259 | },
260 | {
261 | "cell_type": "code",
262 | "execution_count": 0,
263 | "metadata": {
264 | "colab": {},
265 | "colab_type": "code",
266 | "id": "kt6KM_3qpmxp"
267 | },
268 | "outputs": [],
269 | "source": [
270 | "print(fila.empty())"
271 | ]
272 | },
273 | {
274 | "cell_type": "markdown",
275 | "metadata": {
276 | "colab_type": "text",
277 | "id": "Ur-hofH7wkDz"
278 | },
279 | "source": [
280 | "Da mesma forma que podemos tentar colocar um elemento em uma fila já cheia, o Python também permite tentar processar, ou seja, retornar e remover, um elemento de uma fila vazia. \n",
281 | "\n",
282 | "Análogamente ao método `put()`, se tentarmos processar um elemento de uma fila vazia através do método `get()`, este irá esperar entrar um novo elemento para poder, automaticamente, retorná-lo e removê-lo. \n",
283 | "\n",
284 | "Para resolver este problema, também utilizamos o parâmetro `block` ou o método `get_nowait()` e, se a fila estiver vazia, irá resultar na exceção `Empty`."
285 | ]
286 | },
287 | {
288 | "cell_type": "code",
289 | "execution_count": 0,
290 | "metadata": {
291 | "colab": {},
292 | "colab_type": "code",
293 | "id": "cO7pfgMpwwaP"
294 | },
295 | "outputs": [],
296 | "source": [
297 | "fila.get(block=False)"
298 | ]
299 | },
300 | {
301 | "cell_type": "code",
302 | "execution_count": 0,
303 | "metadata": {
304 | "colab": {},
305 | "colab_type": "code",
306 | "id": "nPLw9ndNwsv3"
307 | },
308 | "outputs": [],
309 | "source": [
310 | "fila.get_nowait()"
311 | ]
312 | },
313 | {
314 | "cell_type": "markdown",
315 | "metadata": {
316 | "colab_type": "text",
317 | "id": "uLdVvQ3dpz6I"
318 | },
319 | "source": [
320 | "# Fila de prioridade"
321 | ]
322 | },
323 | {
324 | "cell_type": "markdown",
325 | "metadata": {
326 | "colab_type": "text",
327 | "id": "5N0gyurYp8So"
328 | },
329 | "source": [
330 | "Para entender como funciona a fila de prioridade, podemos usar a mesma analogia descrita anteriormente: a de um atendimento presencial em um banco, no qual muitas vezes é necessário entrar em uma fila. \n",
331 | "\n",
332 | "Nessas filas, além de dar prioridade à primeira pessoa que chegar, também é dada prioridade para alguns tipos de pessoas, como, por exemplo, gestantes, idosos, portadores de necessidades especiais etc. \n",
333 | "\n",
334 | "O TAD fila de prioridade funciona da mesma forma, pois, se tentarmos adicionar um elemento que se caracteriza com uma certa prioridade, este será adicionado no início da fila, respeitando outros elementos prioritários que foram adicionados primeiro.\n",
335 | "\n",
336 | "Esta estrutura é uma implementação do tipo fila e possui todos os mesmos métodos citados anteriormente. Contudo, o que difere uma fila de prioridade de uma fila normal é apenas o fato de que, como o próprio nome já diz, a primeira segue um padrão de prioridade ao adicionarmos e retirarmos elementos da fila."
337 | ]
338 | },
339 | {
340 | "cell_type": "code",
341 | "execution_count": 2,
342 | "metadata": {
343 | "colab": {},
344 | "colab_type": "code",
345 | "id": "ujZCMSunqC6R"
346 | },
347 | "outputs": [],
348 | "source": [
349 | "from queue import PriorityQueue\n",
350 | "filaPrioritaria = PriorityQueue(maxsize=0);"
351 | ]
352 | },
353 | {
354 | "cell_type": "markdown",
355 | "metadata": {
356 | "colab_type": "text",
357 | "id": "g9bgwzslqFuY"
358 | },
359 | "source": [
360 | "Quando adicionamos elementos à fila prioritária, ela irá organizar automaticamente estes elementos de forma crescente, diferente da fila normal.\n"
361 | ]
362 | },
363 | {
364 | "cell_type": "code",
365 | "execution_count": 3,
366 | "metadata": {
367 | "colab": {},
368 | "colab_type": "code",
369 | "id": "Rz8BlaW-qKas"
370 | },
371 | "outputs": [
372 | {
373 | "name": "stdout",
374 | "output_type": "stream",
375 | "text": [
376 | "1\n",
377 | "2\n",
378 | "5\n",
379 | "7\n"
380 | ]
381 | }
382 | ],
383 | "source": [
384 | "#adicionando elementos\n",
385 | "filaPrioritaria.put(1)\n",
386 | "filaPrioritaria.put(5)\n",
387 | "filaPrioritaria.put(7)\n",
388 | "filaPrioritaria.put(2)\n",
389 | "\n",
390 | "#processando os elementos\n",
391 | "while not filaPrioritaria.empty():\n",
392 | " elemento = filaPrioritaria.get()\n",
393 | " print(elemento)"
394 | ]
395 | },
396 | {
397 | "cell_type": "markdown",
398 | "metadata": {
399 | "colab_type": "text",
400 | "id": "SPMyYspLqUj-"
401 | },
402 | "source": [
403 | "# Deque"
404 | ]
405 | },
406 | {
407 | "cell_type": "markdown",
408 | "metadata": {
409 | "colab_type": "text",
410 | "id": "veMmmGlVqWL0"
411 | },
412 | "source": [
413 | "Nesta última parte, iremos ver um TAD mais amplo que a fila, o *deque*. \n",
414 | "\n",
415 | "Vimos que em uma fila, a inserção de um item é feita no final e a sua retirada ocorre no início. \n",
416 | "\n",
417 | "Já o deque permite a inserção e a remoção em ambas as extremidades da estrutura. Por esse motivo, os deques também são conhecidos como double-ended queue, isto é, fila com duas saídas. "
418 | ]
419 | },
420 | {
421 | "cell_type": "markdown",
422 | "metadata": {
423 | "colab_type": "text",
424 | "id": "gxLuKdDkquVc"
425 | },
426 | "source": [
427 | ""
428 | ]
429 | },
430 | {
431 | "cell_type": "markdown",
432 | "metadata": {
433 | "colab_type": "text",
434 | "id": "u_b_eUPHqyes"
435 | },
436 | "source": [
437 | "No Python, utilizamos a implementação deque da classe collections para criar deques e podemos inicializá-los de várias maneiras."
438 | ]
439 | },
440 | {
441 | "cell_type": "code",
442 | "execution_count": 5,
443 | "metadata": {
444 | "colab": {},
445 | "colab_type": "code",
446 | "id": "Gkdc4ZoXq4XB"
447 | },
448 | "outputs": [],
449 | "source": [
450 | "from collections import deque\n",
451 | "dequeVazio = deque()\n",
452 | "dequeLetras = deque(\"jgkdp\")\n",
453 | "dequeNumeros = deque([11,67,3,32,50])\n",
454 | "dequeLimitado = deque([6,12,56], 5)"
455 | ]
456 | },
457 | {
458 | "cell_type": "markdown",
459 | "metadata": {
460 | "colab_type": "text",
461 | "id": "vwJZ4ypxq8OR"
462 | },
463 | "source": [
464 | "Note que, para criar o `dequeLimitado`, definimos um segundo parâmetro. Nesse caso, o tamanho máximo do deque é cinco, ou seja, podemos adicionar até cinco itens ao deque. \n",
465 | "\n",
466 | "Quando não definimos este parâmetro ou definimos como `None`, o deque pode crescer ilimitadamente. O atributo `maxlen` define o tamanho máximo de um deque.\n"
467 | ]
468 | },
469 | {
470 | "cell_type": "code",
471 | "execution_count": 0,
472 | "metadata": {
473 | "colab": {},
474 | "colab_type": "code",
475 | "id": "NXrnbZxPrQsV"
476 | },
477 | "outputs": [],
478 | "source": [
479 | "print(dequeLimitado.maxlen)\n",
480 | "print(dequeLetras.maxlen)"
481 | ]
482 | },
483 | {
484 | "cell_type": "markdown",
485 | "metadata": {
486 | "colab_type": "text",
487 | "id": "f9adyHUBrT1Y"
488 | },
489 | "source": [
490 | "Podemos visualizar ou iterar sobre os elementos de uma `deque`, mas esse não é o uso comum deste TAD:"
491 | ]
492 | },
493 | {
494 | "cell_type": "code",
495 | "execution_count": 10,
496 | "metadata": {
497 | "colab": {},
498 | "colab_type": "code",
499 | "id": "5phLjBdTx7mi"
500 | },
501 | "outputs": [
502 | {
503 | "name": "stdout",
504 | "output_type": "stream",
505 | "text": [
506 | "deque(['j', 'g', 'k', 'd', 'p'])\n",
507 | "j\n",
508 | "g\n",
509 | "k\n",
510 | "d\n",
511 | "p\n"
512 | ]
513 | }
514 | ],
515 | "source": [
516 | "print(dequeLetras)\n",
517 | "for item in dequeLetras:\n",
518 | " print(item)"
519 | ]
520 | },
521 | {
522 | "cell_type": "markdown",
523 | "metadata": {
524 | "colab_type": "text",
525 | "id": "SViqqHe1rdzp"
526 | },
527 | "source": [
528 | "Podemos adicionar elementos ao deque tanto no início quanto no final dele. Para isso, usamos, respectivamente, os métodos `appendleft()` e `append()`. \n",
529 | "\n",
530 | "Além disso, quando um deque está cheio e adicionamos um item à ele, o elemento da ponta oposta a que estamos adicionando o novo item é removido do deque."
531 | ]
532 | },
533 | {
534 | "cell_type": "code",
535 | "execution_count": 11,
536 | "metadata": {
537 | "colab": {},
538 | "colab_type": "code",
539 | "id": "NqQUlnSzrbRj"
540 | },
541 | "outputs": [
542 | {
543 | "name": "stdout",
544 | "output_type": "stream",
545 | "text": [
546 | "deque([61, 0, 6, 12, 56], maxlen=5)\n"
547 | ]
548 | }
549 | ],
550 | "source": [
551 | "dequeLimitado.appendleft(0)\n",
552 | "dequeLimitado.append(42)\n",
553 | "dequeLimitado.appendleft(61)\n",
554 | "print(dequeLimitado)"
555 | ]
556 | },
557 | {
558 | "cell_type": "markdown",
559 | "metadata": {
560 | "colab_type": "text",
561 | "id": "27GIoGlNrzd0"
562 | },
563 | "source": [
564 | "Os métodos `extend()` e `extendleft()` são usados para adicionar mais de um elemento à um deque de uma vez só."
565 | ]
566 | },
567 | {
568 | "cell_type": "code",
569 | "execution_count": 0,
570 | "metadata": {
571 | "colab": {},
572 | "colab_type": "code",
573 | "id": "_4NaTeHgye7L"
574 | },
575 | "outputs": [],
576 | "source": [
577 | "dequeVazio.extend([61,0,12])\n",
578 | "print(dequeVazio)"
579 | ]
580 | },
581 | {
582 | "cell_type": "code",
583 | "execution_count": 0,
584 | "metadata": {
585 | "colab": {},
586 | "colab_type": "code",
587 | "id": "mMqGdT2Lr75U"
588 | },
589 | "outputs": [],
590 | "source": [
591 | "dequeLetras.extendleft(\"oex\")\n",
592 | "print(dequeLetras)"
593 | ]
594 | },
595 | {
596 | "cell_type": "markdown",
597 | "metadata": {
598 | "colab_type": "text",
599 | "id": "yl8oqNFJr_KW"
600 | },
601 | "source": [
602 | "Podemos remover elementos tanto do início quanto do final do deque com os métodos `popleft()` e `pop()`, respectivamente."
603 | ]
604 | },
605 | {
606 | "cell_type": "code",
607 | "execution_count": 0,
608 | "metadata": {
609 | "colab": {},
610 | "colab_type": "code",
611 | "id": "lUdhtwXssE2w"
612 | },
613 | "outputs": [],
614 | "source": [
615 | "dequeLetras.popleft()\n",
616 | "dequeLetras.pop()\n",
617 | "list(dequeLetras)"
618 | ]
619 | },
620 | {
621 | "cell_type": "markdown",
622 | "metadata": {
623 | "colab_type": "text",
624 | "id": "A5XD_MlfsaTF"
625 | },
626 | "source": [
627 | "Usando o método `clear()`, podemos apagar todos os elementos existentes no deque."
628 | ]
629 | },
630 | {
631 | "cell_type": "code",
632 | "execution_count": 0,
633 | "metadata": {
634 | "colab": {},
635 | "colab_type": "code",
636 | "id": "AcDNi2ROse7U"
637 | },
638 | "outputs": [],
639 | "source": [
640 | "dequeVazio.clear()\n",
641 | "print(dequeVazio)"
642 | ]
643 | },
644 | {
645 | "cell_type": "markdown",
646 | "metadata": {
647 | "colab_type": "text",
648 | "id": "mBN6EbBSrogM"
649 | },
650 | "source": [
651 | "Também podemos fazer operações de listas ordenadas manualmente sobre `deques`, como `insert()`, `remove()` e `index()`, mas isto quebra o propósito de uso da `deque`."
652 | ]
653 | },
654 | {
655 | "cell_type": "code",
656 | "execution_count": 12,
657 | "metadata": {
658 | "colab": {},
659 | "colab_type": "code",
660 | "id": "y3vk5ilirstG"
661 | },
662 | "outputs": [
663 | {
664 | "name": "stdout",
665 | "output_type": "stream",
666 | "text": [
667 | "deque([11, 67, 3, 77, 32, 50])\n"
668 | ]
669 | }
670 | ],
671 | "source": [
672 | "dequeNumeros.insert(3,77)\n",
673 | "print(dequeNumeros)"
674 | ]
675 | },
676 | {
677 | "cell_type": "code",
678 | "execution_count": 0,
679 | "metadata": {
680 | "colab": {},
681 | "colab_type": "code",
682 | "id": "yaydwmtBsXJC"
683 | },
684 | "outputs": [],
685 | "source": [
686 | "dequeLimitado.remove(0)\n",
687 | "print(dequeLimitado)"
688 | ]
689 | },
690 | {
691 | "cell_type": "code",
692 | "execution_count": 0,
693 | "metadata": {
694 | "colab": {},
695 | "colab_type": "code",
696 | "id": "PwfeYfTRr0g7"
697 | },
698 | "outputs": [],
699 | "source": [
700 | "print(dequeNumeros.index(77))"
701 | ]
702 | },
703 | {
704 | "cell_type": "markdown",
705 | "metadata": {
706 | "colab_type": "text",
707 | "id": "W7uOgct3shvQ"
708 | },
709 | "source": [
710 | "## Alguns outros métodos"
711 | ]
712 | },
713 | {
714 | "cell_type": "markdown",
715 | "metadata": {
716 | "colab_type": "text",
717 | "id": "xgJgkf8wsoIS"
718 | },
719 | "source": [
720 | "copy(): Cria uma cópia temporária do deque.\n",
721 | "\n"
722 | ]
723 | },
724 | {
725 | "cell_type": "code",
726 | "execution_count": 0,
727 | "metadata": {
728 | "colab": {},
729 | "colab_type": "code",
730 | "id": "7jBL5GSlsyZV"
731 | },
732 | "outputs": [],
733 | "source": [
734 | "deque = dequeNumeros.copy()\n",
735 | "list(deque)"
736 | ]
737 | },
738 | {
739 | "cell_type": "markdown",
740 | "metadata": {
741 | "colab_type": "text",
742 | "id": "o-3-9XF1s1n5"
743 | },
744 | "source": [
745 | "count(): Conta quantas ocorrências existem de um determinado elemento dentro de um deque."
746 | ]
747 | },
748 | {
749 | "cell_type": "code",
750 | "execution_count": 0,
751 | "metadata": {
752 | "colab": {},
753 | "colab_type": "code",
754 | "id": "w5szkio_s7a7"
755 | },
756 | "outputs": [],
757 | "source": [
758 | "print(deque.count(6))"
759 | ]
760 | },
761 | {
762 | "cell_type": "markdown",
763 | "metadata": {
764 | "colab_type": "text",
765 | "id": "Mbttfh2Hs96I"
766 | },
767 | "source": [
768 | "reverse(): Inverte a ordem dos elementos do deque."
769 | ]
770 | },
771 | {
772 | "cell_type": "code",
773 | "execution_count": 0,
774 | "metadata": {
775 | "colab": {},
776 | "colab_type": "code",
777 | "id": "_PuKIFe5tDzX"
778 | },
779 | "outputs": [],
780 | "source": [
781 | "deque.reverse()\n",
782 | "list(deque)"
783 | ]
784 | },
785 | {
786 | "cell_type": "markdown",
787 | "metadata": {
788 | "colab_type": "text",
789 | "id": "frol1FmOtMQm"
790 | },
791 | "source": [
792 | "rotate(): Se o parâmetro passado for um número positivo, o último elemento do deque será agora o primeiro. Caso contrário, ou seja, se o parâmetro for um número negativo, o primeiro elemento do deque será agora o último."
793 | ]
794 | },
795 | {
796 | "cell_type": "code",
797 | "execution_count": 0,
798 | "metadata": {
799 | "colab": {},
800 | "colab_type": "code",
801 | "id": "TzJ-5L_Fy0dN"
802 | },
803 | "outputs": [],
804 | "source": [
805 | "deque.rotate(1)\n",
806 | "list(deque)"
807 | ]
808 | },
809 | {
810 | "cell_type": "code",
811 | "execution_count": 0,
812 | "metadata": {
813 | "colab": {},
814 | "colab_type": "code",
815 | "id": "TwBGjdk0tHyh"
816 | },
817 | "outputs": [],
818 | "source": [
819 | "deque.rotate(-1)\n",
820 | "list(deque)"
821 | ]
822 | },
823 | {
824 | "cell_type": "markdown",
825 | "metadata": {
826 | "colab_type": "text",
827 | "id": "lAsT6A7PtR_w"
828 | },
829 | "source": [
830 | "# Exercícios"
831 | ]
832 | },
833 | {
834 | "cell_type": "markdown",
835 | "metadata": {
836 | "colab_type": "text",
837 | "id": "T3amp4gytj8b"
838 | },
839 | "source": [
840 | "Questão 01) Crie uma fila ilimitada e vazia. Utilizando os métodos put() e get(), faça as seguintes operações nela:\n",
841 | "\n",
842 | "\n",
843 | "1. Insira os números 3, 8, 2 e 4;\n",
844 | "2. Processe (através do método get()) um elemento da fila e o exiba na tela;\n",
845 | "3. Insira os números 5 e 9;\n",
846 | "4. Processe todos os itens restantes na fila até que ela fique vazia novamente."
847 | ]
848 | },
849 | {
850 | "cell_type": "code",
851 | "execution_count": 0,
852 | "metadata": {
853 | "colab": {},
854 | "colab_type": "code",
855 | "id": "wdJ2EazKt3-d"
856 | },
857 | "outputs": [],
858 | "source": []
859 | },
860 | {
861 | "cell_type": "markdown",
862 | "metadata": {
863 | "colab_type": "text",
864 | "id": "STp7Kukjt4np"
865 | },
866 | "source": [
867 | "Questão 02) Similar a questão anterior, crie agora um deque e, utilizando os métodos aprendidos durante o tutorial, faça as seguintes operações nele:\n",
868 | "\n",
869 | "\n",
870 | "1. Insira os números 11, 32, 63 e 8;\n",
871 | "2. Inverta a ordem dos elementos;\n",
872 | "3. Insira, no início, o número 4 e, no final, o número 59;\n",
873 | "4. Remova os elementos 11 e 63;\n",
874 | "5. Troque a posição do último elemento com o primeiro;\n",
875 | "6. Procure e mostre a posição do elemento 32;\n",
876 | "7. Remova todos os elementos do deque."
877 | ]
878 | },
879 | {
880 | "cell_type": "code",
881 | "execution_count": 0,
882 | "metadata": {
883 | "colab": {},
884 | "colab_type": "code",
885 | "id": "yMyn29QuuU5M"
886 | },
887 | "outputs": [],
888 | "source": []
889 | },
890 | {
891 | "cell_type": "markdown",
892 | "metadata": {
893 | "colab_type": "text",
894 | "id": "YR9GDsL6uVXA"
895 | },
896 | "source": [
897 | "Questão 03) Rodolfo, um aluno de TI, estava estudando sobre as estruturas de dados fila e deque. Para facilitar seu aprendizado sobre deque, ele criou funções para algumas operações que podiam ser feitas com a estrutura. Primeiramente, ele implementou uma função que inicializa e retorna um deque. Posteriormente, ele criou quatro funções que, respectivamente, insere no início e no final, e remove no início e no final do deque. Além disso, nas funções de remoção, Rodolfo pensou em, antes de remover o elemento, verificar se o deque estava vazio. Para isso, ele implementou uma função que determinava o tamanho do deque. Porém, Rodolfo é desatento e errou ao implementar algumas funções, confundindo os métodos de fila e deque. Ajude Rodolfo a reajustar as funções para que elas possam funcionar como deveriam.\n"
898 | ]
899 | },
900 | {
901 | "cell_type": "code",
902 | "execution_count": 0,
903 | "metadata": {
904 | "colab": {},
905 | "colab_type": "code",
906 | "id": "Ozm9KGSHudwi"
907 | },
908 | "outputs": [],
909 | "source": [
910 | "import deque\n",
911 | "\n",
912 | "def inicializar():\n",
913 | " return deque\n",
914 | "\n",
915 | "def inserirComeco(deque, elemento):\n",
916 | " deque.putleft(elemento)\n",
917 | " return deque\n",
918 | "\n",
919 | "def inserirFinal(deque, elemento):\n",
920 | " deque.put(elemento)\n",
921 | " return deque\n",
922 | "\n",
923 | "def removerComeco(deque, elemento):\n",
924 | " if tamanho(deque) != 0:\n",
925 | " deque.pop()\n",
926 | " return deque\n",
927 | "\n",
928 | "def removerFinal(deque, elemento):\n",
929 | " if tamanho(deque) != 0:\n",
930 | " deque.popright()\n",
931 | " return deque\n",
932 | "\n",
933 | "def tamanho(deque):\n",
934 | " return deque.qsize()"
935 | ]
936 | },
937 | {
938 | "cell_type": "markdown",
939 | "metadata": {
940 | "colab_type": "text",
941 | "id": "ehrx8w7XuqWc"
942 | },
943 | "source": [
944 | "Questão 4.1) João está na fila de um banco esperando ser atendido. Porém, ele precisa sair em exatas uma hora para uma reunião importante. Sabe-se que um caixa leva 4 minutos para chamar a próxima pessoa da fila. João é a 22ª pessoa esperando ser atendida e o caixa chamou, no momento, a 8ª pessoa da fila. Com o auxílio da estrutura de dados fila, implemente um algoritmo que ajude João a descobrir se ele será atendido a tempo ou se ele deve voltar em um outro horário.\n"
945 | ]
946 | },
947 | {
948 | "cell_type": "code",
949 | "execution_count": 0,
950 | "metadata": {
951 | "colab": {},
952 | "colab_type": "code",
953 | "id": "PgE88ZlyuxwE"
954 | },
955 | "outputs": [],
956 | "source": []
957 | },
958 | {
959 | "cell_type": "markdown",
960 | "metadata": {
961 | "colab_type": "text",
962 | "id": "Hm5y1Z7yuySr"
963 | },
964 | "source": [
965 | "Questão 4.2) Quando o caixa chamou a 14ª pessoa da fila, João percebeu que chegou uma gestante e um idoso ao banco. Estes, como têm prioridade, foram colocados para o início da fila. Sabendo que João pode ficar no banco por mais 36 minutos, o ajude, novamente, a saber se deve esperar ser atendido ou deve voltar em outro momento."
966 | ]
967 | },
968 | {
969 | "cell_type": "code",
970 | "execution_count": 0,
971 | "metadata": {
972 | "colab": {},
973 | "colab_type": "code",
974 | "id": "__St891Hu4on"
975 | },
976 | "outputs": [],
977 | "source": []
978 | }
979 | ],
980 | "metadata": {
981 | "colab": {
982 | "collapsed_sections": [
983 | "5LZAAs_ThZah",
984 | "uLdVvQ3dpz6I",
985 | "SPMyYspLqUj-",
986 | "lAsT6A7PtR_w"
987 | ],
988 | "name": "Fila, fila prioritária e deques.ipynb",
989 | "provenance": [],
990 | "version": "0.3.2"
991 | },
992 | "kernelspec": {
993 | "display_name": "Python 3",
994 | "language": "python",
995 | "name": "python3"
996 | },
997 | "language_info": {
998 | "codemirror_mode": {
999 | "name": "ipython",
1000 | "version": 3
1001 | },
1002 | "file_extension": ".py",
1003 | "mimetype": "text/x-python",
1004 | "name": "python",
1005 | "nbconvert_exporter": "python",
1006 | "pygments_lexer": "ipython3",
1007 | "version": "3.6.8"
1008 | }
1009 | },
1010 | "nbformat": 4,
1011 | "nbformat_minor": 1
1012 | }
1013 |
--------------------------------------------------------------------------------
/notebooks/SortedList.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "colab_type": "text",
7 | "id": "teNuTfzY4fvh"
8 | },
9 | "source": [
10 | "# Listas ordenadas automaticamente\n",
11 | "\n",
12 | "## Entendendo o que é\n",
13 | "A lista ordenada automaticamente é extremamente útil quando queremos resolver problemas onde a ordem dos nossos elementos da lista importa. Ela nos garante que os elementos estarão ordenados, mesmo após feitas quaisquer operações em nossa lista. \n",
14 | "\n",
15 | "A resolução de problemas que envolvem esse tipo de questão, se torna mais eficiente quando utilizamos listas ordenadas, diminuindo o tempo de implementação do código e facilitando a leitura do mesmo. Afinal, você já deve ter tido a experiência de ordenar uma lista de forma manual; quantos loops e condicionais foram criados não é mesmo? **Em suma, quando sua lista precisar de uma ordenação, use uma lista ordenada automaticamente, pois a ordem dos elementos nunca será alterada!!**\n",
16 | "\n",
17 | "Para utilizar listas ordenadas em Python, incluimos uma biblioteca chamada \"sortedcontainers\". Ela nos fornecerá a classe `SortedList`, que criará nossas listas ordenadas. Em Python, a lista ordenada também mantém os dados em ordem crescente como padrão. Além disso, ela aceita elementos duplicados e fornece fácil acesso e indexação dos mesmos.\n"
18 | ]
19 | },
20 | {
21 | "cell_type": "markdown",
22 | "metadata": {
23 | "colab_type": "text",
24 | "id": "ghJ3uYx35Odp"
25 | },
26 | "source": [
27 | "## Primeiros passos\n"
28 | ]
29 | },
30 | {
31 | "cell_type": "markdown",
32 | "metadata": {
33 | "colab_type": "text",
34 | "id": "56gw2f7tB9n8"
35 | },
36 | "source": [
37 | "O primeiro passo é instalar a biblioteca que contém a classe `SortedList`:\n",
38 | "\n",
39 | "> O símbolo de exclamação no começo de uma célula de código diz para o Jupyter executar o código no terminal 👍🏻"
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": null,
45 | "metadata": {
46 | "colab": {
47 | "base_uri": "https://localhost:8080/",
48 | "height": 34
49 | },
50 | "colab_type": "code",
51 | "id": "PRObXPzbAFXm",
52 | "outputId": "908e70a4-8362-4910-99bd-efba5901e3bb"
53 | },
54 | "outputs": [],
55 | "source": [
56 | "!python3 -m pip install sortedcontainers"
57 | ]
58 | },
59 | {
60 | "cell_type": "markdown",
61 | "metadata": {
62 | "colab_type": "text",
63 | "id": "dLBtvey1RCxu"
64 | },
65 | "source": [
66 | "Ótimo! Agora já podemos criar nossa Lista Ordenada:\n"
67 | ]
68 | },
69 | {
70 | "cell_type": "code",
71 | "execution_count": null,
72 | "metadata": {
73 | "colab": {
74 | "base_uri": "https://localhost:8080/",
75 | "height": 34
76 | },
77 | "colab_type": "code",
78 | "id": "BK8BAh0nRVs0",
79 | "outputId": "a02ef043-d0b0-4f90-80f6-9e178a6159ff"
80 | },
81 | "outputs": [],
82 | "source": [
83 | "from sortedcontainers import SortedList\n",
84 | "sl = SortedList()\n",
85 | "\n",
86 | "print(sl)"
87 | ]
88 | },
89 | {
90 | "cell_type": "markdown",
91 | "metadata": {
92 | "colab_type": "text",
93 | "id": "sESsFtumU4oy"
94 | },
95 | "source": [
96 | "Parabéns, você acabou de criar sua primeira lista! \n",
97 | "\n",
98 | "Mas caso você queira iniciar a SortedList já com valores, também é possivel: "
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": null,
104 | "metadata": {
105 | "colab": {
106 | "base_uri": "https://localhost:8080/",
107 | "height": 34
108 | },
109 | "colab_type": "code",
110 | "id": "Z7ElHbg8AIIk",
111 | "outputId": "e4138af4-e7f0-44b9-e2f9-4cf5ffde48c4"
112 | },
113 | "outputs": [],
114 | "source": [
115 | "sl_1 = SortedList([3, 1, 1, 1, 2, 2, 5, 4])\n",
116 | "print(sl_1)"
117 | ]
118 | },
119 | {
120 | "cell_type": "markdown",
121 | "metadata": {
122 | "colab_type": "text",
123 | "id": "Pk2EybaIyolN"
124 | },
125 | "source": [
126 | "Perceba que uma está vazia e outra preenchida , no próximo tópico iremos aprender como manipular nossa lista."
127 | ]
128 | },
129 | {
130 | "cell_type": "markdown",
131 | "metadata": {
132 | "colab_type": "text",
133 | "id": "ixIQOx0R6BKr"
134 | },
135 | "source": [
136 | "# Manipulando uma lista ordenada automaticamente"
137 | ]
138 | },
139 | {
140 | "cell_type": "markdown",
141 | "metadata": {
142 | "colab_type": "text",
143 | "id": "PGyWkY2Yszh2"
144 | },
145 | "source": [
146 | "### Pertinência"
147 | ]
148 | },
149 | {
150 | "cell_type": "markdown",
151 | "metadata": {
152 | "colab_type": "text",
153 | "id": "VL86IDzJtG4m"
154 | },
155 | "source": [
156 | "De forma semelhante ao `set`, na `SortedList` também podemos ver se um elemento pertence a ela: "
157 | ]
158 | },
159 | {
160 | "cell_type": "code",
161 | "execution_count": null,
162 | "metadata": {
163 | "colab": {
164 | "base_uri": "https://localhost:8080/",
165 | "height": 34
166 | },
167 | "colab_type": "code",
168 | "id": "SWt2uQaKs_D3",
169 | "outputId": "a44cd083-5163-46c6-ac3a-e7ef8ea71630"
170 | },
171 | "outputs": [],
172 | "source": [
173 | "3 in sl_1 "
174 | ]
175 | },
176 | {
177 | "cell_type": "code",
178 | "execution_count": null,
179 | "metadata": {
180 | "colab": {
181 | "base_uri": "https://localhost:8080/",
182 | "height": 34
183 | },
184 | "colab_type": "code",
185 | "id": "FZEB7T4iubJi",
186 | "outputId": "7165fdf1-3f64-427d-93cf-ce792c44d637"
187 | },
188 | "outputs": [],
189 | "source": [
190 | "10 in sl_1"
191 | ]
192 | },
193 | {
194 | "cell_type": "markdown",
195 | "metadata": {},
196 | "source": [
197 | "> Buscar em uma lista ordenada automaticamente é mais eficiente que buscar em uma lista ordenada manualmente, mas ainda é menos eficiente que buscar em um conjunto 👍🏻"
198 | ]
199 | },
200 | {
201 | "cell_type": "markdown",
202 | "metadata": {
203 | "colab_type": "text",
204 | "id": "ItjXcr07_K4N"
205 | },
206 | "source": [
207 | "## Adicionando elementos"
208 | ]
209 | },
210 | {
211 | "cell_type": "markdown",
212 | "metadata": {
213 | "colab_type": "text",
214 | "id": "zbWDv2_BdGvs"
215 | },
216 | "source": [
217 | "Podemos adicionar elementos de duas maneiras.\n",
218 | "\n",
219 | "#### `add()`\n",
220 | "\n",
221 | "A primeira é o método `add()`, que recebe como parâmetro somente um argumento.\n",
222 | "\n",
223 | "Ou seja, você somente pode colocar um valor para ser adicionado a lista ordenada:"
224 | ]
225 | },
226 | {
227 | "cell_type": "code",
228 | "execution_count": null,
229 | "metadata": {
230 | "colab": {
231 | "base_uri": "https://localhost:8080/",
232 | "height": 34
233 | },
234 | "colab_type": "code",
235 | "id": "s2jX_HVX_NjX",
236 | "outputId": "91380b2e-54e9-49e7-d6c0-09b18d46cf90"
237 | },
238 | "outputs": [],
239 | "source": [
240 | "sl.add(1)\n",
241 | "print(sl)"
242 | ]
243 | },
244 | {
245 | "cell_type": "markdown",
246 | "metadata": {
247 | "colab_type": "text",
248 | "id": "ekcsYf8fekTO"
249 | },
250 | "source": [
251 | "#### `update()`\n",
252 | "\n",
253 | "Também podemos adicionar com o método `update()`, com a qual que podemos colocar varios valores:"
254 | ]
255 | },
256 | {
257 | "cell_type": "code",
258 | "execution_count": null,
259 | "metadata": {
260 | "colab": {
261 | "base_uri": "https://localhost:8080/",
262 | "height": 34
263 | },
264 | "colab_type": "code",
265 | "id": "2FO9yDCYeiD7",
266 | "outputId": "83b6d597-111f-420c-9e19-46630355696e"
267 | },
268 | "outputs": [],
269 | "source": [
270 | "sl.update([2,3,4,5,6])\n",
271 | "print(sl)"
272 | ]
273 | },
274 | {
275 | "cell_type": "markdown",
276 | "metadata": {
277 | "colab_type": "text",
278 | "id": "vmO2RXNrP2vx"
279 | },
280 | "source": [
281 | "E se adicionarmos um elemento já existente na lista, o que acontece?"
282 | ]
283 | },
284 | {
285 | "cell_type": "code",
286 | "execution_count": null,
287 | "metadata": {
288 | "colab": {
289 | "base_uri": "https://localhost:8080/",
290 | "height": 34
291 | },
292 | "colab_type": "code",
293 | "id": "sqcd-7R4PmkH",
294 | "outputId": "abab1c3f-22cb-4e5c-d944-e2b6db629047"
295 | },
296 | "outputs": [],
297 | "source": [
298 | "sl.add(2)\n",
299 | "print(sl)"
300 | ]
301 | },
302 | {
303 | "cell_type": "markdown",
304 | "metadata": {
305 | "colab_type": "text",
306 | "id": "iggh71GNQCKw"
307 | },
308 | "source": [
309 | "Note que agora temos dois '2'. Diferente do `set()`, a `SortedList` permite a repetição de elementos."
310 | ]
311 | },
312 | {
313 | "cell_type": "markdown",
314 | "metadata": {
315 | "colab_type": "text",
316 | "id": "7ZhkxMoD_Qqs"
317 | },
318 | "source": [
319 | "## Removendo elementos"
320 | ]
321 | },
322 | {
323 | "cell_type": "markdown",
324 | "metadata": {
325 | "colab_type": "text",
326 | "id": "R9mZN5zTY5t8"
327 | },
328 | "source": [
329 | "Existem várias maneiras de remover elementos:\n",
330 | "\n",
331 | "#### `discard()` \n",
332 | "\n",
333 | "Passamos apenas um parâmetro. Se não existir esse valor que você tentou apagar, ele não reporta nada."
334 | ]
335 | },
336 | {
337 | "cell_type": "code",
338 | "execution_count": null,
339 | "metadata": {
340 | "colab": {
341 | "base_uri": "https://localhost:8080/",
342 | "height": 34
343 | },
344 | "colab_type": "code",
345 | "id": "QQoqTa8m_UzG",
346 | "outputId": "7db21909-d700-4298-bb14-ca2b98c8e67f"
347 | },
348 | "outputs": [],
349 | "source": [
350 | "sl.discard(2)\n",
351 | "print(sl)"
352 | ]
353 | },
354 | {
355 | "cell_type": "markdown",
356 | "metadata": {
357 | "colab_type": "text",
358 | "id": "XnoKXfeqnMEp"
359 | },
360 | "source": [
361 | "#### `remove()` \n",
362 | "\n",
363 | "Passamos apenas um parâmetro. Se não existir esse valor que você tentou apagar, ele reporta um `ValueError`."
364 | ]
365 | },
366 | {
367 | "cell_type": "code",
368 | "execution_count": null,
369 | "metadata": {
370 | "colab": {
371 | "base_uri": "https://localhost:8080/",
372 | "height": 299
373 | },
374 | "colab_type": "code",
375 | "id": "oHwpHGmrnLw6",
376 | "outputId": "dacb7b9b-e35d-431d-f855-2a442affdd57"
377 | },
378 | "outputs": [],
379 | "source": [
380 | "sl.remove(256)\n",
381 | "print(sl)"
382 | ]
383 | },
384 | {
385 | "cell_type": "markdown",
386 | "metadata": {
387 | "colab_type": "text",
388 | "id": "hurEGMIyCYn6"
389 | },
390 | "source": [
391 | "#### pop() \n",
392 | "\n",
393 | "É possivel remover elementos de acordo com o seu índice, mas a maneira de utilizar cada uma essas funções é um pouco diferente."
394 | ]
395 | },
396 | {
397 | "cell_type": "code",
398 | "execution_count": null,
399 | "metadata": {
400 | "colab": {},
401 | "colab_type": "code",
402 | "id": "5QrNUni3DLPJ"
403 | },
404 | "outputs": [],
405 | "source": [
406 | "sl.update([1,2,3,4,5])\n",
407 | "print(\"Lista antes de remover o primeiro indice: {}\".format(sl))\n",
408 | "sl.pop(0)\n",
409 | "print(\"Lista depois de remover o primeiro indice: {}\".format(sl))"
410 | ]
411 | },
412 | {
413 | "cell_type": "markdown",
414 | "metadata": {
415 | "colab_type": "text",
416 | "id": "mqRieOir8xR-"
417 | },
418 | "source": [
419 | "#### `clear()` \n",
420 | "\n",
421 | "Remove todos os valores da lista ordenada."
422 | ]
423 | },
424 | {
425 | "cell_type": "code",
426 | "execution_count": null,
427 | "metadata": {
428 | "colab": {},
429 | "colab_type": "code",
430 | "id": "6g28iaDM8w8V"
431 | },
432 | "outputs": [],
433 | "source": [
434 | "sl.clear()\n",
435 | "print(sl)"
436 | ]
437 | },
438 | {
439 | "cell_type": "markdown",
440 | "metadata": {
441 | "colab_type": "text",
442 | "id": "LSPHl9Cw_Yg0"
443 | },
444 | "source": [
445 | "## Estudando os elementos"
446 | ]
447 | },
448 | {
449 | "cell_type": "markdown",
450 | "metadata": {
451 | "colab_type": "text",
452 | "id": "2LdHf5C6Ogpp"
453 | },
454 | "source": [
455 | "Agora que aprendemos a primeira parte da manipulação de uma `SortedList`, vamos dar continuidade ao aprendizado com algumas funções extremamente úteis.\n",
456 | "\n",
457 | "Suponha que ao fazer seus devidos `add`'s e `remove`'s, você queira ver quantas vezes tal elemento apareceu. Imagine fazendo isso com vários \"for\" e variáveis/vetores, uma confusão não é? Mas com o método `count()`, é muito fácil!"
458 | ]
459 | },
460 | {
461 | "cell_type": "code",
462 | "execution_count": null,
463 | "metadata": {
464 | "colab": {},
465 | "colab_type": "code",
466 | "id": "MAMkfi_w_cjd"
467 | },
468 | "outputs": [],
469 | "source": [
470 | "print(sl_1)\n",
471 | "print(sl_1.count(1))\n",
472 | "print(sl_1.count(2))"
473 | ]
474 | },
475 | {
476 | "cell_type": "markdown",
477 | "metadata": {
478 | "colab_type": "text",
479 | "id": "rzATwhiTXk9R"
480 | },
481 | "source": [
482 | "Beleza, nós já sabemos contar os elementos repetidos. Mas e se precisarmos saber onde o elemento está, ou melhor, seu índice? Em Python, esse problema pode ser resolvido com o método `index()`. \n",
483 | "\n",
484 | "Essa função ainda pode receber os parâmetros para procurar do índice N ao índice M (por padrão o N é o começo da lista, e o M o final). A assinatura do método `index` é `index(valor, índice_início, índice_fim)`. \n",
485 | "\n",
486 | "Curiosidade, se o valor não está na lista é relatado uma mensagem de erro, e a função retorna o primeiro índice da ocorrência."
487 | ]
488 | },
489 | {
490 | "cell_type": "code",
491 | "execution_count": null,
492 | "metadata": {
493 | "colab": {},
494 | "colab_type": "code",
495 | "id": "f-Zj2yR_ZO74"
496 | },
497 | "outputs": [],
498 | "source": [
499 | "print(sl_1.index(2))"
500 | ]
501 | },
502 | {
503 | "cell_type": "code",
504 | "execution_count": null,
505 | "metadata": {
506 | "colab": {},
507 | "colab_type": "code",
508 | "id": "z_zJ0H5rbVfz"
509 | },
510 | "outputs": [],
511 | "source": [
512 | "print(sl_1.index(2, 5))"
513 | ]
514 | },
515 | {
516 | "cell_type": "markdown",
517 | "metadata": {
518 | "colab_type": "text",
519 | "id": "_L5uZSeKc5Tp"
520 | },
521 | "source": [
522 | "Podemos também \"pegar\" o conteúdo da `SortedList` pelo índice, parecido como usamos em vetores:"
523 | ]
524 | },
525 | {
526 | "cell_type": "code",
527 | "execution_count": null,
528 | "metadata": {
529 | "colab": {},
530 | "colab_type": "code",
531 | "id": "P4eJ7mkedJim"
532 | },
533 | "outputs": [],
534 | "source": [
535 | "print(sl_1[3])"
536 | ]
537 | },
538 | {
539 | "cell_type": "markdown",
540 | "metadata": {
541 | "colab_type": "text",
542 | "id": "ImnSTJlmGvrm"
543 | },
544 | "source": [
545 | "#### Exercício de fixação"
546 | ]
547 | },
548 | {
549 | "cell_type": "markdown",
550 | "metadata": {
551 | "colab_type": "text",
552 | "id": "oqJKjx91G9LH"
553 | },
554 | "source": [
555 | "Exercícios desse topico\n"
556 | ]
557 | },
558 | {
559 | "cell_type": "markdown",
560 | "metadata": {
561 | "colab_type": "text",
562 | "id": "VLnCEYrTzjuK"
563 | },
564 | "source": [
565 | "## Iterando a `SortedList`"
566 | ]
567 | },
568 | {
569 | "cell_type": "markdown",
570 | "metadata": {
571 | "colab_type": "text",
572 | "id": "khEVSX10ES6j"
573 | },
574 | "source": [
575 | "Você pode iterar a `SortedList` com um `for`: "
576 | ]
577 | },
578 | {
579 | "cell_type": "code",
580 | "execution_count": null,
581 | "metadata": {
582 | "colab": {},
583 | "colab_type": "code",
584 | "id": "ftrEfclVzztW"
585 | },
586 | "outputs": [],
587 | "source": [
588 | "for j in sl:\n",
589 | " print(j)\n",
590 | "print(sl)"
591 | ]
592 | },
593 | {
594 | "cell_type": "markdown",
595 | "metadata": {
596 | "colab_type": "text",
597 | "id": "QJXMVdj8Jamn"
598 | },
599 | "source": [
600 | "Podemos também iterar somente por um intervalo:"
601 | ]
602 | },
603 | {
604 | "cell_type": "code",
605 | "execution_count": null,
606 | "metadata": {
607 | "colab": {},
608 | "colab_type": "code",
609 | "id": "AFjCLYaIJgqQ"
610 | },
611 | "outputs": [],
612 | "source": [
613 | "for j in sl.irange(3,5):\n",
614 | " print(j)"
615 | ]
616 | },
617 | {
618 | "cell_type": "markdown",
619 | "metadata": {
620 | "colab_type": "text",
621 | "id": "IUe1t7WoKGuz"
622 | },
623 | "source": [
624 | "Ou usando o `islice()`, que ao invés de iterar pelo intervalo dos dados, como o `irange()`, utiliza o intervalo dos índices passados como parâmetro: "
625 | ]
626 | },
627 | {
628 | "cell_type": "code",
629 | "execution_count": null,
630 | "metadata": {
631 | "colab": {},
632 | "colab_type": "code",
633 | "id": "mH0LaJJ1L2nv"
634 | },
635 | "outputs": [],
636 | "source": [
637 | "a = SortedList(['b', '3', 't', 'r', 'd'])\n",
638 | "for k in a.islice(2,4):\n",
639 | " print(k)"
640 | ]
641 | },
642 | {
643 | "cell_type": "markdown",
644 | "metadata": {
645 | "colab_type": "text",
646 | "id": "x5p48B80NdIM"
647 | },
648 | "source": [
649 | "Ou"
650 | ]
651 | },
652 | {
653 | "cell_type": "code",
654 | "execution_count": null,
655 | "metadata": {
656 | "colab": {},
657 | "colab_type": "code",
658 | "id": "ieXi9IidNfzL"
659 | },
660 | "outputs": [],
661 | "source": [
662 | "print(a[2:4])"
663 | ]
664 | },
665 | {
666 | "cell_type": "markdown",
667 | "metadata": {
668 | "colab_type": "text",
669 | "id": "5NeT_WPw_dm1"
670 | },
671 | "source": [
672 | "## Pesquisa binária"
673 | ]
674 | },
675 | {
676 | "cell_type": "markdown",
677 | "metadata": {
678 | "colab_type": "text",
679 | "id": "2C4wUuaHQFSo"
680 | },
681 | "source": [
682 | "Agora, depois de estudarmos itens básicos, vamos introduzir um conceito que casa perfeitamente com a função da `SortedList`. Pesquisa ou busca binária é um algoritmo de busca em vetores que realiza sucessivas divisões do espaço de busca comparando o elemento buscado (chave) com o elemento no meio do vetor. Para utilizarmos essa técnica, é necessário que o vetor esteja ordenada. Nada melhor que a `SortedList` para isso! \n",
683 | "\n",
684 | "Para os curiosos e entusiastas, a busca binária funciona da seguinte maneira: se o elemento do meio do vetor for a chave, a busca termina com sucesso. Caso contrário, se o elemento do meio for menor que o elemento buscado, então a busca continua na metade posterior do vetor. E finalmente, se o elemento do meio for maior do que a chave, a busca continua na metade anterior do vetor.\n",
685 | "\n",
686 | "A complexidade desse algoritmo é da ordem de log2 (n) é o tamanho do vetor de busca. Apresenta-se mais eficiente que a Busca linear cuja ordem é O(n)."
687 | ]
688 | },
689 | {
690 | "cell_type": "markdown",
691 | "metadata": {
692 | "colab_type": "text",
693 | "id": "dI_R_5jCYFVk"
694 | },
695 | "source": [
696 | "### Desafio"
697 | ]
698 | },
699 | {
700 | "cell_type": "markdown",
701 | "metadata": {
702 | "colab_type": "text",
703 | "id": "0WKhejnMYNOF"
704 | },
705 | "source": [
706 | "Para aqueles que se interessaram, propomos um desafio para vocês!\n",
707 | "Desenvolva uma função em python que faça uma busca binária em uma `SortedList` e que diga a posição em que um elemento `N` está na `SortedList`. Para isso, aplique os conceitos que vimos.\n",
708 | " \n",
709 | " \n",
710 | "Regras:\n",
711 | "\n",
712 | "* O vetor deve ter 100 elementos gerados por uma função aleatória podendo assumir valores de 0 a 1000\n",
713 | "* Não utilizar (obviamente) a busca linear\n",
714 | "* A função deve informar caso o número informado não esteja na lista\n",
715 | "\n",
716 | "\n"
717 | ]
718 | },
719 | {
720 | "cell_type": "code",
721 | "execution_count": null,
722 | "metadata": {
723 | "colab": {},
724 | "colab_type": "code",
725 | "id": "MrcP86zm_hv-"
726 | },
727 | "outputs": [],
728 | "source": []
729 | },
730 | {
731 | "cell_type": "markdown",
732 | "metadata": {
733 | "colab_type": "text",
734 | "id": "hENZ66Ooa1T7"
735 | },
736 | "source": [
737 | "Você pode testar se realmente a busca binária é eficiente. Rode a função acima com o utilitário \"time\" no terminal do linux ou %time aqui no colab, depois, faça um algoritmo de busca em e compare o runtime de cada um!\n",
738 | "\n",
739 | "> Caso queiram conhecer mais sobre o assunto, acessem https://pt.khanacademy.org/computing/computer-science/algorithms/binary-search/a/binary-search\n"
740 | ]
741 | },
742 | {
743 | "cell_type": "markdown",
744 | "metadata": {
745 | "colab_type": "text",
746 | "id": "ZHc0KKDo_l6w"
747 | },
748 | "source": [
749 | "## Operações com listas ordenadas"
750 | ]
751 | },
752 | {
753 | "cell_type": "markdown",
754 | "metadata": {
755 | "colab_type": "text",
756 | "id": "VMQgB2vscPRu"
757 | },
758 | "source": [
759 | "Também é possivel usar os operadores `+` e `*` com a `SortedList`:\n",
760 | "\n",
761 | "#### União com o operador `+`\n",
762 | "\n",
763 | "Realiza a união de duas listas ordenadas automaticamente. Diferentemente de conjuntos, esta união preserva elementos duplicados: "
764 | ]
765 | },
766 | {
767 | "cell_type": "code",
768 | "execution_count": null,
769 | "metadata": {
770 | "colab": {},
771 | "colab_type": "code",
772 | "id": "2ysdO0Br_p1n"
773 | },
774 | "outputs": [],
775 | "source": [
776 | "sl.clear()\n",
777 | "\n",
778 | "sl = SortedList([1,2,3,4,5])\n",
779 | "sl2 = SortedList([5,6,7,8,9])\n",
780 | "\n",
781 | "print(\"lista1 -> {}\".format(sl))\n",
782 | "print(\"lista2 -> {}\".format(sl2))\n",
783 | "\n",
784 | "print(\"Soma das duas listas -> {}\".format(sl + sl2))"
785 | ]
786 | },
787 | {
788 | "cell_type": "markdown",
789 | "metadata": {
790 | "colab_type": "text",
791 | "id": "gfCPVGcUe8Ns"
792 | },
793 | "source": [
794 | "#### Repetição de elementos com o operador `*` \n",
795 | "\n",
796 | "Repete os elementos da lista `n` vezes:"
797 | ]
798 | },
799 | {
800 | "cell_type": "code",
801 | "execution_count": null,
802 | "metadata": {
803 | "colab": {},
804 | "colab_type": "code",
805 | "id": "Gh9DoGUue7TE"
806 | },
807 | "outputs": [],
808 | "source": [
809 | "print(\"lista antes da multiplicação -> {}\".format(sl))\n",
810 | "mult = sl * 3\n",
811 | "print(\"lista depois da multiplicação -> {}\".format(mult))"
812 | ]
813 | },
814 | {
815 | "cell_type": "markdown",
816 | "metadata": {
817 | "colab_type": "text",
818 | "id": "aZ2D9apN_sm9"
819 | },
820 | "source": [
821 | "# Exercícios\n",
822 | "\n",
823 | "Agora que você já está craque em listas ordenadas, chegou a hora de práticar!"
824 | ]
825 | },
826 | {
827 | "cell_type": "markdown",
828 | "metadata": {
829 | "colab_type": "text",
830 | "id": "12cvqUtBAh4X"
831 | },
832 | "source": [
833 | "\n",
834 | "1 - Crie um programa que faça uma lista de números e retorne a lista e o maior valor da mesma\n",
835 | "\n",
836 | "Exemplo:\n",
837 | "\n",
838 | "Entrada:([1,2,5,23,6,3,6,87])\n",
839 | "\n",
840 | "Saída: 87"
841 | ]
842 | },
843 | {
844 | "cell_type": "code",
845 | "execution_count": null,
846 | "metadata": {
847 | "colab": {},
848 | "colab_type": "code",
849 | "id": "12VS_otgAkCF"
850 | },
851 | "outputs": [],
852 | "source": []
853 | },
854 | {
855 | "cell_type": "markdown",
856 | "metadata": {
857 | "colab_type": "text",
858 | "id": "Mr02hxxgyJnQ"
859 | },
860 | "source": [
861 | " 2 - Crie uma função que recebe duas strings do usuário e que diga se são anagramas ou não. Utilize SortedList() para tal. Pense um pouquinho e verás que é extremamente trivial!\n",
862 | "\n",
863 | "Ex:\n",
864 | "\t\n",
865 | " Entrada - \"roma\", \"amor\"\n",
866 | " Saída - \"São anagramas\"\n",
867 | "\n",
868 | "\tEntrada - \"topa\", \"pato\"\n",
869 | "\tSaída - \"São anagramas\"\n",
870 | "\n",
871 | "\tEntrada - \"sol\", \"lua\"\n",
872 | "\tSaída - \"Não são anagramas\""
873 | ]
874 | },
875 | {
876 | "cell_type": "code",
877 | "execution_count": null,
878 | "metadata": {
879 | "colab": {},
880 | "colab_type": "code",
881 | "id": "HFJWmkV7yV3B"
882 | },
883 | "outputs": [],
884 | "source": []
885 | },
886 | {
887 | "cell_type": "markdown",
888 | "metadata": {
889 | "colab_type": "text",
890 | "id": "LLLXcHPOMGQ-"
891 | },
892 | "source": [
893 | "3 - Dado a lista ordenada [5, 3, 7, 9, 17, 13, 15, 11, 19], faça um programa que peça ao usuário para digitar um valor que deve ser a soma entre 2 valores dessa lista (dois valores diferentes). O programa deve percorrer os valores da lista e caso exista a soma, o mesmo deve exibir a soma, caso não exista deve informar que não existe soma entre os valores da lista igual ao valor informado.\n",
894 | "Ex: \t\n",
895 | "\tEntrada 30\n",
896 | "\tSaída 11 + 19 = 30\n",
897 | "\n",
898 | "\tEntrada 20\n",
899 | "\tSaída 9 + 11 = 20\n",
900 | "\n",
901 | "\tEntrada -1\n",
902 | "\tSaída \"Não existe soma entre os valores da lista que seja igual a -1\"\n",
903 | "\n",
904 | "\tEntrada 40\n",
905 | "\tSaída \"Não existe soma entre os valores da lista que seja igual a 40\""
906 | ]
907 | },
908 | {
909 | "cell_type": "code",
910 | "execution_count": null,
911 | "metadata": {
912 | "colab": {},
913 | "colab_type": "code",
914 | "id": "LuEfwVQjNnBI"
915 | },
916 | "outputs": [],
917 | "source": []
918 | },
919 | {
920 | "cell_type": "markdown",
921 | "metadata": {
922 | "colab_type": "text",
923 | "id": "-AaGXERUHGgd"
924 | },
925 | "source": [
926 | "4 - Desenvolva um programa que mostre quais as três palavras mais frequentes em um texto. A entrada deve ser um texto e o programa deverá exibir uma lista em ordem descrescente das palavras mais utilizadas no texto. "
927 | ]
928 | },
929 | {
930 | "cell_type": "code",
931 | "execution_count": null,
932 | "metadata": {
933 | "colab": {},
934 | "colab_type": "code",
935 | "id": "LuEfwVQjNnBI"
936 | },
937 | "outputs": [],
938 | "source": []
939 | }
940 | ],
941 | "metadata": {
942 | "colab": {
943 | "collapsed_sections": [],
944 | "name": "Notebook 4.ipynb",
945 | "provenance": [],
946 | "toc_visible": true,
947 | "version": "0.3.2"
948 | },
949 | "kernelspec": {
950 | "display_name": "Python 3",
951 | "language": "python",
952 | "name": "python3"
953 | },
954 | "language_info": {
955 | "codemirror_mode": {
956 | "name": "ipython",
957 | "version": 3
958 | },
959 | "file_extension": ".py",
960 | "mimetype": "text/x-python",
961 | "name": "python",
962 | "nbconvert_exporter": "python",
963 | "pygments_lexer": "ipython3",
964 | "version": "3.6.8"
965 | }
966 | },
967 | "nbformat": 4,
968 | "nbformat_minor": 1
969 | }
970 |
--------------------------------------------------------------------------------
/notebooks/set.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "colab_type": "text",
7 | "id": "ilOE4mE2F1E1"
8 | },
9 | "source": [
10 | "# Conjuntos"
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "metadata": {
16 | "colab_type": "text",
17 | "id": "xLuXhXixIRB7"
18 | },
19 | "source": [
20 | "Uma pesquisa foi realizada com os alunos de uma turma de Tecnologia da Informação, perguntando quais idiomas cada aluno falava, dentre inglês, espanhol, francês e alemão.\n",
21 | "\n",
22 | "Com os resultados coletados, deseja-se saber quantos alunos falam somente um idioma. Considerando que a turma tinha apenas 30 alunos, talvez fosse fácil alcançar tal objetivo.\n",
23 | "\n",
24 | "Agora, suponha que essa mesma pesquisa fosse aplicada para todos os alunos da UFRN? E se considerássemos todos os campi da UFRN?\n",
25 | "\n",
26 | "É aí que entram os conjuntos!\n",
27 | "\n",
28 | "Os conjuntos são tipos abstratos de dados (equivalente aos conjuntos matemáticos) que manipulam coleções de elementos únicos, não ordenados e imutáveis."
29 | ]
30 | },
31 | {
32 | "cell_type": "markdown",
33 | "metadata": {
34 | "colab_type": "text",
35 | "id": "oaRQcnnIF_ij"
36 | },
37 | "source": [
38 | "## Primeiros passos"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {
44 | "colab_type": "text",
45 | "id": "ND1SNBnpIwLt"
46 | },
47 | "source": [
48 | "Em Python, um conjunto pode ser criado já com seus elementos declarados, dentro de chaves {} e separando-os por vírgulas.\n",
49 | "\n",
50 | "Também é possível criar um conjunto vazio, com a função construtora ```set()```:"
51 | ]
52 | },
53 | {
54 | "cell_type": "code",
55 | "execution_count": null,
56 | "metadata": {
57 | "colab": {},
58 | "colab_type": "code",
59 | "id": "oi9nn22uIzjb"
60 | },
61 | "outputs": [],
62 | "source": [
63 | "meu_conjunto = {1, 2, 3, 4, 5}\n",
64 | "conjunto_vazio = set()\n",
65 | "\n",
66 | "print(meu_conjunto)\n",
67 | "print(conjunto_vazio)"
68 | ]
69 | },
70 | {
71 | "cell_type": "markdown",
72 | "metadata": {
73 | "colab_type": "text",
74 | "id": "EhoNN5CHJp01"
75 | },
76 | "source": [
77 | "Um conjunto pode ter elementos de diferentes tipos:"
78 | ]
79 | },
80 | {
81 | "cell_type": "code",
82 | "execution_count": null,
83 | "metadata": {
84 | "colab": {},
85 | "colab_type": "code",
86 | "id": "9pyi5-BDJtbW"
87 | },
88 | "outputs": [],
89 | "source": [
90 | "meu_conjunto = {1, 3.3, 'a', 'palavra'}\n",
91 | "print(meu_conjunto)"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {
97 | "colab_type": "text",
98 | "id": "LXrM-DDVKEhx"
99 | },
100 | "source": [
101 | "Além disso, um conjunto pode ser criado com a função construtora ```set()``` tendo como parâmetro um tipo iterável de dados (string, lista, dicionário, tuplas, etc...). \n",
102 | "\n",
103 | "Nesse caso, o conjunto formado possui os elementos únicos do tipo iterávels fornecido como parâmetro:"
104 | ]
105 | },
106 | {
107 | "cell_type": "code",
108 | "execution_count": null,
109 | "metadata": {
110 | "colab": {},
111 | "colab_type": "code",
112 | "id": "kSvywhQAKQjz"
113 | },
114 | "outputs": [],
115 | "source": [
116 | "meu_conjunto = set('Hello,world')\n",
117 | "print(meu_conjunto)"
118 | ]
119 | },
120 | {
121 | "cell_type": "markdown",
122 | "metadata": {},
123 | "source": [
124 | "### Iterando sobre seus elementos"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "metadata": {},
130 | "source": [
131 | "Você pode iterar sobre os elementos de um conjunto usando um `for`:"
132 | ]
133 | },
134 | {
135 | "cell_type": "code",
136 | "execution_count": null,
137 | "metadata": {},
138 | "outputs": [],
139 | "source": [
140 | "for x in meu_conjunto:\n",
141 | " print(x)"
142 | ]
143 | },
144 | {
145 | "cell_type": "markdown",
146 | "metadata": {},
147 | "source": [
148 | "Como não há preservação de ordem dos elementos de um `set`, você não pode acessar seus elementos por índices ou confiar em qual ordem eles estarão:"
149 | ]
150 | },
151 | {
152 | "cell_type": "code",
153 | "execution_count": null,
154 | "metadata": {},
155 | "outputs": [],
156 | "source": [
157 | "meu_conjunto[0]"
158 | ]
159 | },
160 | {
161 | "cell_type": "markdown",
162 | "metadata": {
163 | "colab_type": "text",
164 | "id": "sO4uG468TeYY"
165 | },
166 | "source": [
167 | "#### Exercícios w3r - [w3resource list](https://www.w3resource.com/python-exercises/python-functions-exercises.php)"
168 | ]
169 | },
170 | {
171 | "cell_type": "markdown",
172 | "metadata": {
173 | "colab_type": "text",
174 | "id": "1jkEksPIU02F"
175 | },
176 | "source": [
177 | "1 - Escreva um procedimento que determine o maior número dentro de um conjunto de 7 números."
178 | ]
179 | },
180 | {
181 | "cell_type": "code",
182 | "execution_count": null,
183 | "metadata": {
184 | "colab": {},
185 | "colab_type": "code",
186 | "id": "P5mpbHUnVQok"
187 | },
188 | "outputs": [],
189 | "source": []
190 | },
191 | {
192 | "cell_type": "markdown",
193 | "metadata": {
194 | "colab_type": "text",
195 | "id": "roGVGDLhVubL"
196 | },
197 | "source": [
198 | "2 - Escreva um procedimento que some todos os elementos de um conjunto."
199 | ]
200 | },
201 | {
202 | "cell_type": "code",
203 | "execution_count": null,
204 | "metadata": {
205 | "colab": {},
206 | "colab_type": "code",
207 | "id": "h4V_VlBtV13T"
208 | },
209 | "outputs": [],
210 | "source": []
211 | },
212 | {
213 | "cell_type": "markdown",
214 | "metadata": {
215 | "colab_type": "text",
216 | "id": "R7DdPaF8V2ny"
217 | },
218 | "source": [
219 | "3 - Escreva um procedimento que multiplique todos os elementos de um conjunto."
220 | ]
221 | },
222 | {
223 | "cell_type": "code",
224 | "execution_count": null,
225 | "metadata": {},
226 | "outputs": [],
227 | "source": []
228 | },
229 | {
230 | "cell_type": "markdown",
231 | "metadata": {},
232 | "source": [
233 | "> Como os exercícios acima são bem comuns no dia-a-dia, Python tem procedimentos-padrão para resolvê-los. Pesquise sobre eles e veja como fica bem mais simples de resolver essas questões 👍🏻"
234 | ]
235 | },
236 | {
237 | "cell_type": "markdown",
238 | "metadata": {
239 | "colab_type": "text",
240 | "id": "y38humahGCyX"
241 | },
242 | "source": [
243 | "## Como usar o `set`"
244 | ]
245 | },
246 | {
247 | "cell_type": "markdown",
248 | "metadata": {
249 | "colab_type": "text",
250 | "id": "MPksi_HuLOKV"
251 | },
252 | "source": [
253 | "### Adição e remoção de elementos \n",
254 | "\n",
255 | "Depois de ser criado, um conjunto pode ser modificado, tendo elementos adicionados ou removidos dele.\n",
256 | "\n",
257 | "Para adicionar um elemento, utiliza-se o método ```add()```. \n",
258 | "\n",
259 | "> Confira na sessão de **Extras** os comandos `update` para adição de múltiplos elementos."
260 | ]
261 | },
262 | {
263 | "cell_type": "code",
264 | "execution_count": null,
265 | "metadata": {
266 | "colab": {},
267 | "colab_type": "code",
268 | "id": "4rRjt12NLQjF"
269 | },
270 | "outputs": [],
271 | "source": [
272 | "meu_conjunto = {1, 2, 3}\n",
273 | "meu_conjunto.add(4)\n",
274 | "print(meu_conjunto)"
275 | ]
276 | },
277 | {
278 | "cell_type": "markdown",
279 | "metadata": {
280 | "colab_type": "text",
281 | "id": "AEfOVzgmLel7"
282 | },
283 | "source": [
284 | "Já para remover, tem-se o método ```remove()```, que elimina do conjunto o elemento passado como parâmetro:"
285 | ]
286 | },
287 | {
288 | "cell_type": "code",
289 | "execution_count": null,
290 | "metadata": {
291 | "colab": {},
292 | "colab_type": "code",
293 | "id": "zuRXcU69LoLI"
294 | },
295 | "outputs": [],
296 | "source": [
297 | "meu_conjunto = {1, 2, 3}\n",
298 | "meu_conjunto.remove(3)\n",
299 | "print(meu_conjunto) "
300 | ]
301 | },
302 | {
303 | "cell_type": "markdown",
304 | "metadata": {
305 | "colab_type": "text",
306 | "id": "aQ69iaVnL8xR"
307 | },
308 | "source": [
309 | "E, se por algum motivo, o usuário tentar remover um elemento que não existe no conjunto?"
310 | ]
311 | },
312 | {
313 | "cell_type": "code",
314 | "execution_count": null,
315 | "metadata": {
316 | "colab": {},
317 | "colab_type": "code",
318 | "id": "PqpKn982L9nt"
319 | },
320 | "outputs": [],
321 | "source": [
322 | "meu_conjunto = {1, 2, 3}\n",
323 | "meu_conjunto.remove(4)\n",
324 | "print(meu_conjunto) "
325 | ]
326 | },
327 | {
328 | "cell_type": "markdown",
329 | "metadata": {
330 | "colab_type": "text",
331 | "id": "kvUgGNk2MEn5"
332 | },
333 | "source": [
334 | "Você recebeu o erro `KeyError`, justamente porque o `remove()` só remove elementos que fazem parte do conjunto. \n",
335 | "\n",
336 | "Para essa situação, existe o método `discard()`, que tenta remover um elemento sem disparar erros caso ele não exista."
337 | ]
338 | },
339 | {
340 | "cell_type": "code",
341 | "execution_count": null,
342 | "metadata": {
343 | "colab": {},
344 | "colab_type": "code",
345 | "id": "e5zb9PrhMbIz"
346 | },
347 | "outputs": [],
348 | "source": [
349 | "meu_conjunto = {1, 2, 3}\n",
350 | "meu_conjunto.discard(2)\n",
351 | "print(meu_conjunto) \n",
352 | "meu_conjunto.discard(4)\n",
353 | "print(meu_conjunto) "
354 | ]
355 | },
356 | {
357 | "cell_type": "markdown",
358 | "metadata": {
359 | "colab_type": "text",
360 | "id": "YM2I76jGMmgU"
361 | },
362 | "source": [
363 | "Também existe o método `clear()`, que remove todos os elementos do conjunto:"
364 | ]
365 | },
366 | {
367 | "cell_type": "code",
368 | "execution_count": null,
369 | "metadata": {
370 | "colab": {},
371 | "colab_type": "code",
372 | "id": "GJN1pENNMoC9"
373 | },
374 | "outputs": [],
375 | "source": [
376 | "meu_conjunto = {1, 2, 3}\n",
377 | "print(meu_conjunto)\n",
378 | "meu_conjunto.clear()\n",
379 | "print(meu_conjunto) "
380 | ]
381 | },
382 | {
383 | "cell_type": "markdown",
384 | "metadata": {
385 | "colab_type": "text",
386 | "id": "_rqm_nCuNHR7"
387 | },
388 | "source": [
389 | "### Cardinalidade \n",
390 | "\n",
391 | "O número de elementos de um conjunto pode ser calculado com o procedimento `len()`:"
392 | ]
393 | },
394 | {
395 | "cell_type": "code",
396 | "execution_count": null,
397 | "metadata": {
398 | "colab": {},
399 | "colab_type": "code",
400 | "id": "dWl_Bzd6NJgW"
401 | },
402 | "outputs": [],
403 | "source": [
404 | "meu_conjunto = {1, 2, 3}\n",
405 | "print (len(meu_conjunto))"
406 | ]
407 | },
408 | {
409 | "cell_type": "markdown",
410 | "metadata": {
411 | "colab_type": "text",
412 | "id": "5r_4F-SzHlWC"
413 | },
414 | "source": [
415 | "### União\n",
416 | "\n",
417 | "Assim como na matemática, a união de `sets` concatena os elementos dos conjuntos em questão em um só.\n",
418 | "\n",
419 | "Em Python, a operação é realizada através do método `union()` ou do operador `|`.\n",
420 | "\n",
421 | "> A união de conjuntos significa literalmente identificar os elementos presentes em um conjunto **ou** no outro. É por isso que podemos usar o operador lógico `|` 🙃 \n",
422 | "\n",
423 | "No exemplo abaixo, temos dois conjuntos distintos `a` e `b` que desejamos unir:"
424 | ]
425 | },
426 | {
427 | "cell_type": "code",
428 | "execution_count": null,
429 | "metadata": {
430 | "colab": {},
431 | "colab_type": "code",
432 | "id": "SGT6bQNbHudf"
433 | },
434 | "outputs": [],
435 | "source": [
436 | "a = {1, 2, 3, 4}\n",
437 | "b = {3, 4, 5, 6}\n",
438 | "\n",
439 | "# operando com union()\n",
440 | "print(a.union(b))\n",
441 | "\n",
442 | "# operando com |\n",
443 | "print(a | b)"
444 | ]
445 | },
446 | {
447 | "cell_type": "markdown",
448 | "metadata": {
449 | "colab_type": "text",
450 | "id": "tJkYrP_QISog"
451 | },
452 | "source": [
453 | "### Intersecção\n",
454 | "\n",
455 | "Fazendo a interseção entre dois `sets`, obtemos o conjunto de elementos em comum entre eles.\n",
456 | "\n",
457 | "Podemos realizar essa operação através do método `intersection()` ou do operador `&`.\n",
458 | "\n",
459 | "> A intersecção de conjuntos significa literalmente identificar os elementos presentes em um conjunto **e** no outro. É por isso que podemos usar o operador lógico `&` 🙃 "
460 | ]
461 | },
462 | {
463 | "cell_type": "code",
464 | "execution_count": null,
465 | "metadata": {
466 | "colab": {},
467 | "colab_type": "code",
468 | "id": "l68oYejMIe-7"
469 | },
470 | "outputs": [],
471 | "source": [
472 | "# operando com intersection()\n",
473 | "print(a.intersection(b))\n",
474 | "\n",
475 | "#operando com &\n",
476 | "print(a & b)"
477 | ]
478 | },
479 | {
480 | "cell_type": "markdown",
481 | "metadata": {
482 | "colab_type": "text",
483 | "id": "cE5JZpt1IlJv"
484 | },
485 | "source": [
486 | "### Diferença\n",
487 | "\n",
488 | "Com a diferença entre `a` e `b`, obtemos o conjunto de elementos que pertencem ao conjunto `a`, mas não pertencem ao conjunto `b`.\n",
489 | "\n",
490 | "Realizamos esta operação usando o método `difference()` ou o operador `-`. \n",
491 | "\n",
492 | "**Note que `a - b` não é necessariamente igual a `b - a`.**\n",
493 | "\n",
494 | "> A diferença de conjuntos significa literalmente identificar os elementos presentes em um conjunto, **menos** os que estejam no outro. É por isso que podemos usar o operador aritmético `-` 🙃 "
495 | ]
496 | },
497 | {
498 | "cell_type": "code",
499 | "execution_count": null,
500 | "metadata": {
501 | "colab": {},
502 | "colab_type": "code",
503 | "id": "uFDjRpwsI1E2"
504 | },
505 | "outputs": [],
506 | "source": [
507 | "# operando com difference()\n",
508 | "print(a.difference(b))\n",
509 | "print(b.difference(a))\n",
510 | "\n",
511 | "# operando com -\n",
512 | "print(a - b)\n",
513 | "print(b - a)"
514 | ]
515 | },
516 | {
517 | "cell_type": "markdown",
518 | "metadata": {
519 | "colab_type": "text",
520 | "id": "XPfzCP-xI61N"
521 | },
522 | "source": [
523 | "### Diferença simétrica\n",
524 | "\n",
525 | "A diferença simétrica representa a união dos elementos de dois conjuntos, com exceção daqueles que estejam na intersecção entre estes dois conjuntos.\n",
526 | "\n",
527 | "É possível realizar esta operação através do método `symmetric_difference()` ou do operador `^`.\n",
528 | "\n",
529 | "> A diferença simétrica de conjuntos significa literalmente identificar os elementos presentes **ou** em um conjunto **ou** no outro. É por isso que podemos usar o operador lógico `^`, que representa o **ou exclusivo** 🙃 "
530 | ]
531 | },
532 | {
533 | "cell_type": "code",
534 | "execution_count": null,
535 | "metadata": {
536 | "colab": {},
537 | "colab_type": "code",
538 | "id": "rVty_0EcJBug"
539 | },
540 | "outputs": [],
541 | "source": [
542 | "# operando com symmetric_difference()\n",
543 | "print(a.symmetric_difference(b))\n",
544 | "\n",
545 | "# operando com ^\n",
546 | "print(a ^ b)"
547 | ]
548 | },
549 | {
550 | "cell_type": "markdown",
551 | "metadata": {
552 | "colab_type": "text",
553 | "id": "VlxTDCtWJbyd"
554 | },
555 | "source": [
556 | "### Pertinência\n",
557 | "\n",
558 | "Utilizando o operador de pertinência `in`, podemos verificar se um elemento está ou não em um conjunto:"
559 | ]
560 | },
561 | {
562 | "cell_type": "code",
563 | "execution_count": null,
564 | "metadata": {
565 | "colab": {},
566 | "colab_type": "code",
567 | "id": "s_szy9T1Jf0V"
568 | },
569 | "outputs": [],
570 | "source": [
571 | "1 in a"
572 | ]
573 | },
574 | {
575 | "cell_type": "code",
576 | "execution_count": null,
577 | "metadata": {
578 | "colab": {},
579 | "colab_type": "code",
580 | "id": "rVWrE64JJv8z"
581 | },
582 | "outputs": [],
583 | "source": [
584 | "5 in a"
585 | ]
586 | },
587 | {
588 | "cell_type": "markdown",
589 | "metadata": {},
590 | "source": [
591 | "Também podemos combinar o operador `in` com o operador lógico `not`:"
592 | ]
593 | },
594 | {
595 | "cell_type": "code",
596 | "execution_count": null,
597 | "metadata": {
598 | "colab": {},
599 | "colab_type": "code",
600 | "id": "NFFeJzOnQSoj"
601 | },
602 | "outputs": [],
603 | "source": [
604 | "8 not in a"
605 | ]
606 | },
607 | {
608 | "cell_type": "markdown",
609 | "metadata": {},
610 | "source": [
611 | "### Continência e disjunção"
612 | ]
613 | },
614 | {
615 | "cell_type": "markdown",
616 | "metadata": {
617 | "colab_type": "text",
618 | "id": "utuzvdZyKk-L"
619 | },
620 | "source": [
621 | "Enquanto o operador `in` verifica se um elemento pertence a um conjunto, o `set` oferece três métodos para testar relações entre conjuntos: "
622 | ]
623 | },
624 | {
625 | "cell_type": "markdown",
626 | "metadata": {},
627 | "source": [
628 | "1. `issubset()` ou `<=`: testa se um conjunto está contido em outro, ou seja, se um conjunto é um subconjunto do outro."
629 | ]
630 | },
631 | {
632 | "cell_type": "code",
633 | "execution_count": null,
634 | "metadata": {
635 | "colab": {},
636 | "colab_type": "code",
637 | "id": "C7509kyLKpn-"
638 | },
639 | "outputs": [],
640 | "source": [
641 | "c = {1, 2}\n",
642 | "\n",
643 | "# operando com issubset()\n",
644 | "if c.issubset(a): \n",
645 | " print(\"C é subconjunto de A, pois C está contido em A.\")\n",
646 | "else:\n",
647 | " print(\"C não é subconjunto de A, pois C não está contido em A.\")\n",
648 | "\n",
649 | "# operando com <=\n",
650 | "if not c <= a: \n",
651 | " print(\"C não é subconjunto de A, pois C não está contido em A.\")\n",
652 | "else:\n",
653 | " print(\"C é subconjunto de A, pois C está contido em A.\")"
654 | ]
655 | },
656 | {
657 | "cell_type": "markdown",
658 | "metadata": {
659 | "colab_type": "text",
660 | "id": "NK1SRkIyK3sG"
661 | },
662 | "source": [
663 | "2. `issuperset()` ou `>=`: testa se um conjunto contém o outro, ou seja, se um conjunto é um superconjunto do outro."
664 | ]
665 | },
666 | {
667 | "cell_type": "code",
668 | "execution_count": null,
669 | "metadata": {
670 | "colab": {},
671 | "colab_type": "code",
672 | "id": "7eaiyrLfLCsF"
673 | },
674 | "outputs": [],
675 | "source": [
676 | "# operando com issuperset()\n",
677 | "if a.issuperset(c):\n",
678 | " print(\"A é superconjunto de C, pois A contém C.\")\n",
679 | "else:\n",
680 | " print(\"A não é superconjunto de C, pois A não contém C.\")\n",
681 | " \n",
682 | "# operando com >=\n",
683 | "if not a >= c:\n",
684 | " print(\"A não é superconjunto de C, pois A não contém C.\")\n",
685 | "else:\n",
686 | " print(\"A é superconjunto de C, pois A contém C.\")"
687 | ]
688 | },
689 | {
690 | "cell_type": "markdown",
691 | "metadata": {},
692 | "source": [
693 | "> As relações `<=` e `>=` são simétricas, então `a >= b` equivale a `b <= a`."
694 | ]
695 | },
696 | {
697 | "cell_type": "markdown",
698 | "metadata": {
699 | "colab_type": "text",
700 | "id": "9QjPx2nZMOgj"
701 | },
702 | "source": [
703 | "3. `isdisjoint()`: testa se dois conjuntos são disjuntos, ou seja, se a interseção entre eles é vazia."
704 | ]
705 | },
706 | {
707 | "cell_type": "code",
708 | "execution_count": null,
709 | "metadata": {
710 | "colab": {},
711 | "colab_type": "code",
712 | "id": "dcknyU00MUa2"
713 | },
714 | "outputs": [],
715 | "source": [
716 | "if c.isdisjoint(a):\n",
717 | " print(\"C e A são disjuntos, pois sua interseção é vazia.\")\n",
718 | "else:\n",
719 | " print(\"C e A não são disjuntos, pois sua interseção não é vazia.\")\n",
720 | "if c.isdisjoint(b):\n",
721 | " print(\"C e B são disjuntos, pois sua interseção é vazia.\")\n",
722 | "else:\n",
723 | " print(\"C e B não são disjuntos, pois sua interseção não é vazia.\")"
724 | ]
725 | },
726 | {
727 | "cell_type": "markdown",
728 | "metadata": {
729 | "colab_type": "text",
730 | "id": "va2_qr9VRCxm"
731 | },
732 | "source": [
733 | "# Exercícios"
734 | ]
735 | },
736 | {
737 | "cell_type": "markdown",
738 | "metadata": {
739 | "colab_type": "text",
740 | "id": "0ZrVKl2LRHPn"
741 | },
742 | "source": [
743 | "1 - Agora que já temos um bom conhecimentos sobre os conjuntos, voltemos ao exemplo da introdução. \n",
744 | "\n",
745 | "Os dados sobre conhecimento em diversos idiomas pelos estudantes da UFRN são guardados em um banco de dados. \n",
746 | "\n",
747 | "Após consulta a essa base de dados, a matrícula dos alunos foram salvas nos conjuntos relativos aos idiomas que cada um fala:"
748 | ]
749 | },
750 | {
751 | "cell_type": "code",
752 | "execution_count": null,
753 | "metadata": {
754 | "colab": {},
755 | "colab_type": "code",
756 | "id": "YgOmzQPrRdHa"
757 | },
758 | "outputs": [],
759 | "source": [
760 | "ingles = {2017992691, 2014731077, 2016127320, 2017673650, 2017675600, 2016071490, 2015763941,2018124856, 2014240183, 2015069118, 2017397627, 2018257434, 2018146279,2018336479, 2016255160, 2016191681, 2017462010, 2015267990, 2018353177,2016316106, 2017534024, 2017435227, 2018485174, 2017511916, 2018252953, 2018230360, 2015896310, 2016403233, 2018036952, 2018223748, 2017106407, 2018928865, 2015808443, 2015490023, 2014680801, 2016797947, 2017169550, 2017741705, 2016449433, 2018701674, 2018681674, 2018822119, 2015629894, 2018552429, 2014160569, 2014812342, 2015241433, 2015633224, 2015938370, 2014994808, 2018682286, 2014920254, 2017952048, 2014899143, 2018459199, 2015659561, 2018886010, 2016111302, 2018528579, 2017559038, 2018248638, 2015560871, 2014569332, 2018652276, 2016701261, 2016308042, 2016310173, 2017705448, 2014399415, 2016268450, 2017608181, 2015981561, 2014964705, 2014655030, 2017687958, 2016162852, 2017223176, 2014759427, 2017290535, 2017031946, 2017042504, 2018916372, 2017757689, 2014922487, 2016080164, 2014792539, 2016110301, 2015200433, 2015667306, 2014891106, 2014748251, 2018911399, 2015008915, 2014976823, 2018870448}\n",
761 | "espanhol = {2017992691, 2014731077, 2016127320, 2017673650, 2017675600, 2016071490, 2015763941, 2015365994, 2014728861, 2014152867, 2018044073, 2015856913, 2018124856, 2014240183, 2017534024, 2017435227, 2018485174, 2017511916, 2018252953, 2018230360, 2015896310, 2016403233, 2018036952, 2018223748, 2017106407, 2018928865, 2015808443, 2015490023, 2014680801, 2016797947, 2017169550, 2017741705, 2016449433, 2018701674, 2018681674, 2018822119, 2015629894, 2018552429, 2014160569, 2014812342, 2015241433, 2015633224, 2015938370, 2014994808, 2018682286, 2014920254, 2017952048, 2014899143, 2018459199, 2015659561, 2018886010, 2016111302, 2018528579, 2017559038, 2018248638, 2015560871, 2014569332, 2018652276, 2016701261, 2016308042, 2016310173, 2017705448, 2014399415, 2016268450}\n",
762 | "frances = {2016268450, 2017608181, 2015981561, 2014964705, 2014655030, 2017687958, 2016162852, 2017223176, 2014759427, 2017290535, 2017031946, 2017042504, 2018916372, 2017757689, 2014922487, 2016080164, 2014792539, 2016110301, 2015200433, 2015667306, 2014891106, 2014748251, 2018911399, 2015008915, 2014976823, 2018870448, 2018230360, 2015896310, 2016403233, 2018036952, 2018223748, 2017106407, 2018928865, 2015808443, 2015490023, 2014680801, 2016797947, 2017169550, 2017741705, 2016449433, 2018701674, 2018681674, 2018822119, 2015629894, 2018552429,}\n",
763 | "alemao = {2015763941, 2015365994, 2014728861, 2014152867, 2018044073, 2015856913, 2018124856, 2014240183, 2015069118, 2017397627, 2018257434, 2018146279,2018336479, 2016255160, 2016191681, 2017462010, 2015267990, 2018353177,2016316106, 2017534024, 2017435227, 2018485174, 2017511916, 2018252953, 2018230360, 2015896310, 2016403233, 2018036952, 2018223748, 2017106407, 2018928865, 2015808443, 2015490023, 2014680801, 2016797947, 2017169550, 2017741705, 2016449433, 2018701674, 2018681674, 2018822119, 2015629894, 2018552429, 2014160569, 2014812342, 2015241433, 2015633224, 2015938370, 2014994808, 2018682286, 2014920254}"
764 | ]
765 | },
766 | {
767 | "cell_type": "markdown",
768 | "metadata": {
769 | "colab_type": "text",
770 | "id": "ZP7aLZTtRrBs"
771 | },
772 | "source": [
773 | "1.1 - Calcule quantos alunos falam apenas inglês e espanhol:"
774 | ]
775 | },
776 | {
777 | "cell_type": "code",
778 | "execution_count": null,
779 | "metadata": {
780 | "colab": {},
781 | "colab_type": "code",
782 | "id": "cOpD-g4aRsQB"
783 | },
784 | "outputs": [],
785 | "source": []
786 | },
787 | {
788 | "cell_type": "markdown",
789 | "metadata": {
790 | "colab_type": "text",
791 | "id": "EAbcOQ2DRv4A"
792 | },
793 | "source": [
794 | "1.2 - Calcule quantos alunos falam apenas um idioma:"
795 | ]
796 | },
797 | {
798 | "cell_type": "code",
799 | "execution_count": null,
800 | "metadata": {
801 | "colab": {},
802 | "colab_type": "code",
803 | "id": "I0XlgJdrR0Ve"
804 | },
805 | "outputs": [],
806 | "source": []
807 | },
808 | {
809 | "cell_type": "markdown",
810 | "metadata": {
811 | "colab_type": "text",
812 | "id": "Z_HROn0QRs_W"
813 | },
814 | "source": [
815 | "1.3 - Calcule quantos alunos falam dois idiomas:"
816 | ]
817 | },
818 | {
819 | "cell_type": "code",
820 | "execution_count": null,
821 | "metadata": {
822 | "colab": {},
823 | "colab_type": "code",
824 | "id": "TmNx8vBCRz1I"
825 | },
826 | "outputs": [],
827 | "source": []
828 | },
829 | {
830 | "cell_type": "markdown",
831 | "metadata": {
832 | "colab_type": "text",
833 | "id": "Bx2KGgZKSKKR"
834 | },
835 | "source": [
836 | "Já imaginou realizar esses cálculos sem o ```set()```? Com certeza, teríamos mais trabalho.\n",
837 | "\n",
838 | "Nesse exercício, vimos uma das utilidades dos conjuntos, que é realizar operações. Outra ocasião em que pode ser bastante útil é na remoção de elementos repetidos de uma sequência. Para entender melhor, faça o exercício 2:"
839 | ]
840 | },
841 | {
842 | "cell_type": "markdown",
843 | "metadata": {
844 | "colab_type": "text",
845 | "id": "GsztDDtzSLUQ"
846 | },
847 | "source": [
848 | "2 - **[OBI - 2012]** Certa vez, numa aula, a professora passou um filme para os alunos assistirem. Durante este filme, ela passou uma lista de presença em sua sala para verificar a presença dos alunos, onde cada aluno deveria inserir apenas seu número de registro. Alguns alunos contudo, como possuem amigos que fogem da aula, decidiram ser camaradas e inseriram os números de registro de seus amigos fujões. O problema é que muitos alunos são amigos de alunos que fogem da aula e alguns números de registro acabaram sendo repetidamente inseridos na lista de presença. Além de tudo, alguns dos alunos que se esperava que não estivessem na aula de fato estavam!\n",
849 | "\n",
850 | "A professora, ao notar que a lista de presença continha alguns números repetidos, ficou sem entender, mas decidiu dar um voto de confiança e dar presença a todos os alunos cujos números de registro estavam na lista. Como são muitos alunos na sala e muitos números com repetição, ela pediu a sua ajuda para determinar o total de alunos que receberam presença na aula."
851 | ]
852 | },
853 | {
854 | "cell_type": "markdown",
855 | "metadata": {
856 | "colab_type": "text",
857 | "id": "WpucsZKZS7Sn"
858 | },
859 | "source": [
860 | "**Entrada**\n",
861 | "\n",
862 | "A primeira linha da entrada contém um número inteiro N , que informa a quantidade de números de registro que apareceram na lista de presença. Cada uma das N linhas seguintes contém um número de registro Vi que foi inserido na lista de presença.\n",
863 | "\n",
864 | "**Saída**\n",
865 | "Seu programa deve imprimir uma única linha, contendo apenas um número inteiro, o número de alunos que receberam presença."
866 | ]
867 | },
868 | {
869 | "cell_type": "markdown",
870 | "metadata": {
871 | "colab_type": "text",
872 | "id": "ptPTsS7kTRyu"
873 | },
874 | "source": [
875 | "| Entrada \t| Saída \t|\n",
876 | "|--------------------\t|-------\t|\n",
877 | "| 3
2
3
1| 3 \t|"
878 | ]
879 | },
880 | {
881 | "cell_type": "code",
882 | "execution_count": null,
883 | "metadata": {
884 | "colab": {},
885 | "colab_type": "code",
886 | "id": "q7GEc59NTeVk"
887 | },
888 | "outputs": [],
889 | "source": []
890 | },
891 | {
892 | "cell_type": "markdown",
893 | "metadata": {
894 | "colab_type": "text",
895 | "id": "hGQloYI5TfFe"
896 | },
897 | "source": [
898 | "3 - **[Continuação]** No dia seguinte, a professora deu um grande sermão para os seus alunos, que se comprometeram a não fugir mais das aulas.\n",
899 | "Passada uma semana, a professora passou mais um filme para os seus alunos assistirem e a mesma situação se repetiu. Chateada, ela decidiu que, dessa vez, daria falta nos alunos que tinham registro repetido na lista de presença. Mais uma vez, ela pediu a sua ajuda para determinar o total de alunos que receberam presença na aula."
900 | ]
901 | },
902 | {
903 | "cell_type": "markdown",
904 | "metadata": {
905 | "colab_type": "text",
906 | "id": "MxbSUPtcTpSQ"
907 | },
908 | "source": [
909 | "**Entrada**\n",
910 | "\n",
911 | "A primeira linha da entrada contém um número inteiro N , que informa a quantidade de números de registro que apareceram na lista de presença. Cada uma das N linhas seguintes contém um número de registro Vi que foi inserido na lista de presença.\n",
912 | "\n",
913 | "**Saída**\n",
914 | "\n",
915 | "Seu programa deve imprimir uma única linha, contendo apenas um número inteiro, o número de alunos que receberam presença.\n"
916 | ]
917 | },
918 | {
919 | "cell_type": "markdown",
920 | "metadata": {
921 | "colab_type": "text",
922 | "id": "R3BU7OJbTyJq"
923 | },
924 | "source": [
925 | "| Entrada \t| Saída \t|\n",
926 | "|--------------------\t| -------\t|\n",
927 | "| 15
1
0
5
6
0
12
25
6
2
6
5
0
25
13
2 | 4 \t|"
928 | ]
929 | },
930 | {
931 | "cell_type": "code",
932 | "execution_count": null,
933 | "metadata": {
934 | "colab": {},
935 | "colab_type": "code",
936 | "id": "3YeNjIU4LC3C"
937 | },
938 | "outputs": [],
939 | "source": []
940 | },
941 | {
942 | "cell_type": "markdown",
943 | "metadata": {
944 | "colab_type": "text",
945 | "id": "G21D68zTU3Vd"
946 | },
947 | "source": [
948 | "3 - João e Maria possuem um dado de 12 faces e gostam de jogar com ele da seguinte forma:\n",
949 | "- João lança o dado e o número da face virada para cima é eliminado;\n",
950 | "- depois, Maria repete o processo. Caso tire um número que já foi eliminado, nada acontece;\n",
951 | "- assim continuam até que não restem mais números para serem eliminados;\n",
952 | "- ganha quem conseguir eliminar o último número.
\n",
953 | "Faça um programa que simule esse jogo"
954 | ]
955 | },
956 | {
957 | "cell_type": "code",
958 | "execution_count": null,
959 | "metadata": {
960 | "colab": {},
961 | "colab_type": "code",
962 | "id": "abFSN0BPWQcp"
963 | },
964 | "outputs": [],
965 | "source": []
966 | },
967 | {
968 | "cell_type": "markdown",
969 | "metadata": {
970 | "colab_type": "text",
971 | "id": "twjw_hF1N24I"
972 | },
973 | "source": [
974 | "# Extras"
975 | ]
976 | },
977 | {
978 | "cell_type": "markdown",
979 | "metadata": {
980 | "colab_type": "text",
981 | "id": "hBuv6GdgUXyX"
982 | },
983 | "source": [
984 | "**Update**: Modifica o conjunto A para possuir os elementos de A $\\cup$ B"
985 | ]
986 | },
987 | {
988 | "cell_type": "code",
989 | "execution_count": null,
990 | "metadata": {
991 | "colab": {},
992 | "colab_type": "code",
993 | "id": "jGYVaBaTUkf3"
994 | },
995 | "outputs": [],
996 | "source": [
997 | "a = {1, 2, 3, 4}\n",
998 | "b = {3, 4, 5, 6}\n",
999 | "print(a)\n",
1000 | "print(b)\n",
1001 | "print(a.union(b))\n",
1002 | "a.update(b)\n",
1003 | "print(a)\n",
1004 | "print(b)"
1005 | ]
1006 | },
1007 | {
1008 | "cell_type": "markdown",
1009 | "metadata": {
1010 | "colab_type": "text",
1011 | "id": "UznGU1E6Uv4j"
1012 | },
1013 | "source": [
1014 | "A função ```update()``` pode ser utilizada com outras funções, sendo escrita como sufixo. \n",
1015 | "\n",
1016 | "Nesse caso, ela sobrescreve o conjunto A para ser equivalente a operação desejada. \n",
1017 | "\n",
1018 | "Por exemplo:"
1019 | ]
1020 | },
1021 | {
1022 | "cell_type": "code",
1023 | "execution_count": null,
1024 | "metadata": {
1025 | "colab": {},
1026 | "colab_type": "code",
1027 | "id": "q0XJwlsPUyxF"
1028 | },
1029 | "outputs": [],
1030 | "source": [
1031 | "a = {1, 2, 3, 4}\n",
1032 | "b = {3, 4, 5, 6}\n",
1033 | "print(a)\n",
1034 | "print(b)\n",
1035 | "print(a.intersection(b))\n",
1036 | "a.intersection_update(b)\n",
1037 | "print(a)\n",
1038 | "print(b)"
1039 | ]
1040 | },
1041 | {
1042 | "cell_type": "code",
1043 | "execution_count": null,
1044 | "metadata": {
1045 | "colab": {},
1046 | "colab_type": "code",
1047 | "id": "FzOkoEYSelGa"
1048 | },
1049 | "outputs": [],
1050 | "source": [
1051 | "a = {1, 2, 3, 4}\n",
1052 | "b = {3, 4, 5, 6}\n",
1053 | "print(a)\n",
1054 | "print(b)\n",
1055 | "print(a.difference(b))\n",
1056 | "a.difference_update(b)\n",
1057 | "print(a)\n",
1058 | "print(b)"
1059 | ]
1060 | },
1061 | {
1062 | "cell_type": "code",
1063 | "execution_count": null,
1064 | "metadata": {
1065 | "colab": {},
1066 | "colab_type": "code",
1067 | "id": "TO7DCjp6elTr"
1068 | },
1069 | "outputs": [],
1070 | "source": [
1071 | "a = {1, 2, 3, 4}\n",
1072 | "b = {3, 4, 5, 6}\n",
1073 | "print(a)\n",
1074 | "print(b)\n",
1075 | "print(a.symmetric_difference(b))\n",
1076 | "a.symmetric_difference_update(b)\n",
1077 | "print(a)\n",
1078 | "print(b)"
1079 | ]
1080 | },
1081 | {
1082 | "cell_type": "markdown",
1083 | "metadata": {
1084 | "colab_type": "text",
1085 | "id": "ufNwjr4gSTmx"
1086 | },
1087 | "source": [
1088 | "**Frozenset**: funciona, em linhas gerais, como um conjunto, mas com a diferença de que não pode ser alterado.
\n",
1089 | "Leia mais em: [frozenset](https://www.programiz.com/python-programming/methods/built-in/frozenset)"
1090 | ]
1091 | }
1092 | ],
1093 | "metadata": {
1094 | "colab": {
1095 | "collapsed_sections": [],
1096 | "name": "Conjuntos.ipynb",
1097 | "provenance": [],
1098 | "toc_visible": true,
1099 | "version": "0.3.2"
1100 | },
1101 | "kernelspec": {
1102 | "display_name": "Python 3",
1103 | "language": "python",
1104 | "name": "python3"
1105 | },
1106 | "language_info": {
1107 | "codemirror_mode": {
1108 | "name": "ipython",
1109 | "version": 3
1110 | },
1111 | "file_extension": ".py",
1112 | "mimetype": "text/x-python",
1113 | "name": "python",
1114 | "nbconvert_exporter": "python",
1115 | "pygments_lexer": "ipython3",
1116 | "version": "3.6.8"
1117 | }
1118 | },
1119 | "nbformat": 4,
1120 | "nbformat_minor": 1
1121 | }
1122 |
--------------------------------------------------------------------------------
/notebooks/tree.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "colab_type": "text",
7 | "id": "LFquYPImCGo4"
8 | },
9 | "source": [
10 | "# Árvores em Python: O que são e como se organizam."
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "metadata": {
16 | "colab_type": "text",
17 | "id": "gcGOl22GGzWv"
18 | },
19 | "source": [
20 | " Uma Tree é uma estrutura de dados que tem como principal utilidade o fato de cada dado estar ligado a outro de forma hierarquica. \n",
21 | "De certa forma, as Trees se organizam como as árvores da natureza, tanto que daí vem o nome \"Tree\", com a diferença de começarem a partir das raízes e irem descendo até as folhas, como uma \"árvore invertida\".\n",
22 | "\n",
23 | "\n",
24 | "\n",
25 | "\n",
26 | "A palavra \"árvore\" (\"*tree*\", em inglês) é usada na computação quando falamos de uma forma em que os dados podem ser organizados. Nas árvores, temos nódulos (\"*nodes*\", em inglês) com ligações para outros nodes, e eles são os dados que queremos organizar. A raíz, \"*root*\", é o nódulo original, de onde todos os outros partem. Os termos \"*child*\" (plural \"*children*\"), \"*parent*\" (plural \"*parents*\") e \"sibling\" (plural \"*siblings*\") correspondem a \"filho\", \"pai\" e \"irmão\", respectivamente, e servem para ilustrar a idéia da organização vertical de uma arvore, onde os nodes que dão origem a outros (abaixo dele) são \"pais\", os que surgem dele, seus \"filhos\" e filhos de um mesmo pai são \"irmãos\". Por fim, \"*leaf*\" (plural \"*leaves*\") é o termo usado para um node \"final\" que não é pai de nenhum outro, da mesma forma que não surgem galhos a partir das folhas de uma árvore. Nas árvores, cada node ***pode*** ter um ou mais nodes abaixo dele (filhos) mas somente um acima (pai).\n",
27 | "\n",
28 | "\n",
29 | "\n",
30 | "Python não tem um suporte já pronto para essa estrutura de dados, então iremos usar uma biblioteca para facilitar o aprendizado de como as trees são usadas. A biblioteca selecionada para ser usada nesse tutorial é \"*[anytree](https://pypi.org/project/anytree/)*\". ***(como python depende de bibliotecas para usar trees, os comandos variam dependendo de sua escolha e são de menor importância para seu aprendizado)***\n",
31 | "\n",
32 | "***É DE EXTREMA IMPORTÂNCIA QUE O CÓDIGO ABAIXO SEJA RODADO***"
33 | ]
34 | },
35 | {
36 | "cell_type": "code",
37 | "execution_count": null,
38 | "metadata": {
39 | "colab": {
40 | "base_uri": "https://localhost:8080/",
41 | "height": 214
42 | },
43 | "colab_type": "code",
44 | "id": "O1RvDxkuRSjg",
45 | "outputId": "4d55a0c9-5453-4da4-8870-e7a5d66528d6"
46 | },
47 | "outputs": [],
48 | "source": [
49 | "#SEMPRE rode isso quando abrir o notebook para garantir que irá funcionar apropriadamente\n",
50 | "!pip install anytree\n",
51 | "!pip install anytree --user"
52 | ]
53 | },
54 | {
55 | "cell_type": "markdown",
56 | "metadata": {
57 | "colab_type": "text",
58 | "id": "TAo0w9-Nf9_F"
59 | },
60 | "source": [
61 | "# Métodos"
62 | ]
63 | },
64 | {
65 | "cell_type": "markdown",
66 | "metadata": {
67 | "colab_type": "text",
68 | "id": "PvIFsqmpgFbk"
69 | },
70 | "source": [
71 | "Para começar, devemos importar alguns certos elementos de nossa biblioteca. Ative a cécula abaixo para prosseguir:"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "execution_count": null,
77 | "metadata": {
78 | "colab": {},
79 | "colab_type": "code",
80 | "id": "Z8OvrC-cgtoW"
81 | },
82 | "outputs": [],
83 | "source": [
84 | "from anytree import Node, RenderTree"
85 | ]
86 | },
87 | {
88 | "cell_type": "markdown",
89 | "metadata": {
90 | "colab_type": "text",
91 | "id": "8I5uYB48gtK8"
92 | },
93 | "source": [
94 | "Agora podemos começar a programar! Vamos começar criando um *node*. A sintaxe usada pela \"anytree\" é:\n",
95 | "> node_name = Node(node_data, parent = node_parent)\n",
96 | "\n"
97 | ]
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": null,
102 | "metadata": {
103 | "colab": {},
104 | "colab_type": "code",
105 | "id": "OY_6oXdDiKis"
106 | },
107 | "outputs": [],
108 | "source": [
109 | "pessoas = Node(\"Pessoas no IMD\") #criando o node root"
110 | ]
111 | },
112 | {
113 | "cell_type": "markdown",
114 | "metadata": {
115 | "colab_type": "text",
116 | "id": "eZFFmL3pi4E0"
117 | },
118 | "source": [
119 | "Note que 'pessoas' em minúsculo é o nome pelo qual iremos identificar o node dentro do código, e a string 'Pessoas no IMD' é o conteúdo de tal node. Percebeu que faltou a parte \n",
120 | "> ' `, parent = ~node-parent~` ' ?\n",
121 | "\n",
122 | "Como estamos criando o primeiro node, o root, ele não pode/deve ter nenhum pai.\n",
123 | "\n",
124 | "Agora, vamos criar mais nodes para preencher nossa árvore!"
125 | ]
126 | },
127 | {
128 | "cell_type": "code",
129 | "execution_count": null,
130 | "metadata": {
131 | "colab": {},
132 | "colab_type": "code",
133 | "id": "IgmNNR5Qn22D"
134 | },
135 | "outputs": [],
136 | "source": [
137 | "estudantes = Node(\"Estudantes\", parent = pessoas) #\n",
138 | "\n",
139 | "aluno_1 = Node(\"Aluno 1\", parent = estudantes) #\n",
140 | "\n",
141 | "elementos_pessoais = Node(\"Informações pessoais\", parent = aluno_1) # \n",
142 | "elementos_academicos = Node(\"Dados academicos\", parent = aluno_1) #\n",
143 | "\n",
144 | "matricula = Node(123456789, parent = elementos_pessoais) #\n",
145 | "nome = Node(\"Joãozinho\", parent = elementos_pessoais) #\n",
146 | "endereco = Node(\"Rua dos bobos nº0\", parent = elementos_pessoais) #\n",
147 | "\n",
148 | "cursos = Node(\"Disciplinas\", parent = elementos_academicos) #\n",
149 | "projetos = Node(\"Projetos acadêmicos\", parent = elementos_academicos) #\n",
150 | "\n",
151 | "edb = Node(\"Estrutura de Dados Básicas\", parent = cursos) #\n",
152 | "fmc2 = Node(\"FMC II\", parent = cursos) \n",
153 | "lp1 = Node(\"Linguagem de Programação I\", parent = cursos) #"
154 | ]
155 | },
156 | {
157 | "cell_type": "markdown",
158 | "metadata": {
159 | "colab_type": "text",
160 | "id": "bDi-sRVgW7Jp"
161 | },
162 | "source": [
163 | "Vejamos como ficou nossa Tree estudantes"
164 | ]
165 | },
166 | {
167 | "cell_type": "code",
168 | "execution_count": null,
169 | "metadata": {
170 | "colab": {
171 | "base_uri": "https://localhost:8080/",
172 | "height": 231
173 | },
174 | "colab_type": "code",
175 | "id": "9nzDeNO0XCWy",
176 | "outputId": "6fbffd42-5764-402d-8a89-95e59a63e08d"
177 | },
178 | "outputs": [],
179 | "source": [
180 | "print(RenderTree(estudantes)) #usamos a função RenderTree para printar nossa Tree. Usamos como parâmetro o primeiro Node que desejamos printar, e a função vai printar ele e todas as suas Children"
181 | ]
182 | },
183 | {
184 | "cell_type": "markdown",
185 | "metadata": {
186 | "colab_type": "text",
187 | "id": "qmepfQ2NnQMq"
188 | },
189 | "source": [
190 | "Antes de seguirmos para o próximo exercício, vamos introduzir um outro tipo de Node, o AnyNode. A única diferença em relação a estrutura é que enquanto o Node demanda obrigatoriamente um nome, o AnyNode não o faz. Além disso o AnyNode tem uma forma de printar um pouco diferente."
191 | ]
192 | },
193 | {
194 | "cell_type": "markdown",
195 | "metadata": {
196 | "colab_type": "text",
197 | "id": "Rm5C260jYCNT"
198 | },
199 | "source": [
200 | "Neste outro exemplo, vamos atribuir outros atributos aos nossos Nodes.\n",
201 | "\n",
202 | "Podemos atribuir quantos atributos quisermos e podemos usar qualquer tipo, seja int, float, string, lista..."
203 | ]
204 | },
205 | {
206 | "cell_type": "code",
207 | "execution_count": null,
208 | "metadata": {
209 | "colab": {},
210 | "colab_type": "code",
211 | "id": "-DdnUSgWnmhn"
212 | },
213 | "outputs": [],
214 | "source": [
215 | "from anytree import AnyNode"
216 | ]
217 | },
218 | {
219 | "cell_type": "code",
220 | "execution_count": null,
221 | "metadata": {
222 | "colab": {},
223 | "colab_type": "code",
224 | "id": "PvQI80pGXtep"
225 | },
226 | "outputs": [],
227 | "source": [
228 | "subtenente=AnyNode(Patente=\"Subtenente\",salario=\"6169,00\",categoria=\"Praças\",tarefas=[\"Orientar o treino\",\"Receber o general\"])\n",
229 | "\n",
230 | "sargento=AnyNode(Patente=\"Primeiro Sargento\",salario=\"5483,00\",categoria=\"Praças\",parent=subtenente)\n",
231 | "\n",
232 | "taifeiro_mor=AnyNode(Patente=\"taifeiro_mor\",salario=\"2627,00\",categoria=\"Praças\",parent=sargento)\n",
233 | "cabo=AnyNode(Patente=\"cabo\",salario=\"2627,00\",categoria=\"Praças\",parent=sargento)\n",
234 | "\n",
235 | "taifeiro_1classe=AnyNode(Patente=\"taifeiro de primeira classe\",salario=\"2325,00\",categoria=\"Praças\",parent=taifeiro_mor)\n",
236 | "taifeiro_2classe=AnyNode(Patente=\"taifeiro de segunda classe\",salario=\"2210,00\",categoria=\"Praças\",parent=taifeiro_1classe)\n",
237 | "soldado=AnyNode(Patente=\"Soldado\",salario=\"1560,00\",categoria=\"Praças\",parent=cabo)"
238 | ]
239 | },
240 | {
241 | "cell_type": "markdown",
242 | "metadata": {
243 | "colab_type": "text",
244 | "id": "-JOumxbba9em"
245 | },
246 | "source": [
247 | "Vejamos como ficou:\n",
248 | "(lembrando que isso é só uma aproximação da hierarquia militar)"
249 | ]
250 | },
251 | {
252 | "cell_type": "code",
253 | "execution_count": null,
254 | "metadata": {
255 | "colab": {
256 | "base_uri": "https://localhost:8080/",
257 | "height": 142
258 | },
259 | "colab_type": "code",
260 | "id": "P_Y7uDLIa17n",
261 | "outputId": "5fa09c5c-f8bc-4eb0-e8d4-47c50f4a32b1"
262 | },
263 | "outputs": [],
264 | "source": [
265 | "print(RenderTree(subtenente))"
266 | ]
267 | },
268 | {
269 | "cell_type": "markdown",
270 | "metadata": {
271 | "colab_type": "text",
272 | "id": "Q6SXp9YYbgOd"
273 | },
274 | "source": [
275 | "Note que não temos nenhum oficial em nossa Tree, para corrigir isso devemos colocar alguem com patente acima de subtentente, ou seja: devemos adicionar um Parent ao Node subtenente."
276 | ]
277 | },
278 | {
279 | "cell_type": "code",
280 | "execution_count": null,
281 | "metadata": {
282 | "colab": {},
283 | "colab_type": "code",
284 | "id": "1gUdGYGQcM77"
285 | },
286 | "outputs": [],
287 | "source": [
288 | "primeiro_tenente=AnyNode(Patente=\"Primeiro tenente\",salario=\"7796,00\",categoria=\"Oficiais subalternos\",tarefas=[\"Comandar o pelotão\",\"gerenciar o quartel número 4\"])\n",
289 | "segundo_tenente=AnyNode(Patente=\"Segundo tenente\",salario=\"7490,00\",categoria=\"Oficiais subalternos\",parent=primeiro_tenente, taferas=[\"Auxiliar na gerencia do quartel número 4\"])\n",
290 | "aspirante_a_oficial=AnyNode(Patente=\"Aspirante a oficial\",salario=\"6993,00\",categoria=\"Oficiais subalternos\",parent=primeiro_tenente, taferas=[\"Auxiliar no comando do pelotão\"])\n",
291 | "#agora adicionando os oficiais à nossa tree:\n",
292 | "subtenente.parent=aspirante_a_oficial\n"
293 | ]
294 | },
295 | {
296 | "cell_type": "code",
297 | "execution_count": null,
298 | "metadata": {
299 | "colab": {
300 | "base_uri": "https://localhost:8080/",
301 | "height": 196
302 | },
303 | "colab_type": "code",
304 | "id": "zjG7zo8Fddra",
305 | "outputId": "98f87d85-b170-455f-c540-aec8fd12d1ef"
306 | },
307 | "outputs": [],
308 | "source": [
309 | "print(RenderTree(primeiro_tenente))"
310 | ]
311 | },
312 | {
313 | "cell_type": "markdown",
314 | "metadata": {
315 | "colab_type": "text",
316 | "id": "AD9Pi5N-duHP"
317 | },
318 | "source": [
319 | "Mas digamos que eu tenha acabado de ser promovido para sargento e só queira saber em quem eu posso mandar, vejamos:"
320 | ]
321 | },
322 | {
323 | "cell_type": "code",
324 | "execution_count": null,
325 | "metadata": {
326 | "colab": {
327 | "base_uri": "https://localhost:8080/",
328 | "height": 124
329 | },
330 | "colab_type": "code",
331 | "id": "2noauV58evVk",
332 | "outputId": "202b89c0-d304-4214-e7b6-63cbcd01b4ae"
333 | },
334 | "outputs": [],
335 | "source": [
336 | "print(RenderTree(sargento))"
337 | ]
338 | },
339 | {
340 | "cell_type": "markdown",
341 | "metadata": {
342 | "colab_type": "text",
343 | "id": "UraK709OelTk"
344 | },
345 | "source": [
346 | "# Exercícios de fixação"
347 | ]
348 | },
349 | {
350 | "cell_type": "markdown",
351 | "metadata": {
352 | "colab_type": "text",
353 | "id": "-_Siobi-Jx-E"
354 | },
355 | "source": [
356 | "Vamos criar uma árvore simples. Para começar, devemos lembrar de importar os seguintes elementos:"
357 | ]
358 | },
359 | {
360 | "cell_type": "markdown",
361 | "metadata": {
362 | "colab_type": "text",
363 | "id": "r4k2b4qYhsMb"
364 | },
365 | "source": [
366 | " ***Primeiro exercício: ***\n",
367 | "\n",
368 | " Faça uma Tree com as últimas três gerações masculinas de sua família (seu avô, tios-avô, pai, tios, etc...)"
369 | ]
370 | },
371 | {
372 | "cell_type": "code",
373 | "execution_count": null,
374 | "metadata": {
375 | "colab": {},
376 | "colab_type": "code",
377 | "id": "fHPiKNjiRYEn"
378 | },
379 | "outputs": [],
380 | "source": [
381 | "#primeiro exercício"
382 | ]
383 | },
384 | {
385 | "cell_type": "markdown",
386 | "metadata": {
387 | "colab_type": "text",
388 | "id": "Er0LmB5rpM--"
389 | },
390 | "source": [
391 | "Agora vamos aprender outra forma, uma mais rápida, de criar Trees. \n",
392 | "\n",
393 | "\n",
394 | "O método children (usando como exemplo uma versão simplificada da hierarquia católica):\n"
395 | ]
396 | },
397 | {
398 | "cell_type": "code",
399 | "execution_count": null,
400 | "metadata": {
401 | "colab": {
402 | "base_uri": "https://localhost:8080/",
403 | "height": 124
404 | },
405 | "colab_type": "code",
406 | "id": "1hA7X2HQll8U",
407 | "outputId": "9887ae7c-f31e-4301-f3f4-5b2d303fc40e"
408 | },
409 | "outputs": [],
410 | "source": [
411 | "Papa = AnyNode(nome=\"Papa\",children=[\n",
412 | " AnyNode(nome=\"Arcebispo\",children=[\n",
413 | " AnyNode(nome=\"Bispo\",children=[\n",
414 | " AnyNode(nome=\"Padre Vigário\"),AnyNode(nome=\"Padre Paroco\",children=[AnyNode(nome=\"fiéis\")\n",
415 | " ])\n",
416 | " ])\n",
417 | " ])\n",
418 | "])\n",
419 | "print(RenderTree(Papa))"
420 | ]
421 | },
422 | {
423 | "cell_type": "markdown",
424 | "metadata": {
425 | "colab_type": "text",
426 | "id": "8eB4Y_NRh03S"
427 | },
428 | "source": [
429 | "***Segundo exercício:***\n",
430 | "\n",
431 | "Monte uma Tree, usando os Nodes e a técnica que preferir, baseado na imagem a seguir. Ela contém a hierarquia de um grupo mafioso asiático conhecido como Triad.\n",
432 | "\n",
433 | ""
434 | ]
435 | },
436 | {
437 | "cell_type": "code",
438 | "execution_count": null,
439 | "metadata": {
440 | "colab": {},
441 | "colab_type": "code",
442 | "id": "j0q3Ql7ZRbUQ"
443 | },
444 | "outputs": [],
445 | "source": [
446 | "#segundo exercício"
447 | ]
448 | },
449 | {
450 | "cell_type": "code",
451 | "execution_count": null,
452 | "metadata": {
453 | "colab": {},
454 | "colab_type": "code",
455 | "id": "ExLRgxGMdoLr"
456 | },
457 | "outputs": [],
458 | "source": []
459 | },
460 | {
461 | "cell_type": "markdown",
462 | "metadata": {
463 | "colab_type": "text",
464 | "id": "wLdc58AxHIvK"
465 | },
466 | "source": [
467 | "**Terceiro exercício:**\n",
468 | "\n",
469 | "Por fim, faça uma Tree com todas as matérias que você já pagou até agora e seus pre-requisitos.\n",
470 | "\n",
471 | "*Dica:* Comece usando seu nome como Root, depois coloque as matérias introdutórias tendo como parent seu nome e assim por diante."
472 | ]
473 | },
474 | {
475 | "cell_type": "code",
476 | "execution_count": null,
477 | "metadata": {
478 | "colab": {},
479 | "colab_type": "code",
480 | "id": "Sjs5r9wDH_gV"
481 | },
482 | "outputs": [],
483 | "source": [
484 | "#terceiro exercício"
485 | ]
486 | },
487 | {
488 | "cell_type": "markdown",
489 | "metadata": {
490 | "colab_type": "text",
491 | "id": "Ltl4I57Xi4n0"
492 | },
493 | "source": [
494 | "# Respostas"
495 | ]
496 | },
497 | {
498 | "cell_type": "markdown",
499 | "metadata": {
500 | "colab_type": "text",
501 | "id": "50jVmzxgi6yd"
502 | },
503 | "source": [
504 | "### Exercício 3:"
505 | ]
506 | },
507 | {
508 | "cell_type": "code",
509 | "execution_count": null,
510 | "metadata": {
511 | "colab": {
512 | "base_uri": "https://localhost:8080/",
513 | "height": 367
514 | },
515 | "colab_type": "code",
516 | "id": "oz73lbk_i-g0",
517 | "outputId": "67fbea2b-539d-4f5d-9dfa-de8a6895991f"
518 | },
519 | "outputs": [],
520 | "source": [
521 | "from anytree import Node,AnyNode, RenderTree\n",
522 | "\n",
523 | "dragon_head = AnyNode(nome = \"Mestre da montanha\", cargo = \"Líder\")\n",
524 | "vanguardista = AnyNode(nome = \"Vanguardista\", cargo = \"Chefe de operações\", parent = dragon_head)\n",
525 | "dep_mestre_montanha = AnyNode(nome = \"Deputado do mestre da montanha\", cargo = \"Representante\", parent = dragon_head)\n",
526 | "mestre_incesario = AnyNode(nome = \"Mestre incesário\", cargo = \"Mestre de cerimônias\", parent = dragon_head)\n",
527 | "helice_de_papel_branco = AnyNode(nome = \"Hélice de papel branco\", cargo = \"Administrador\", parent = dep_mestre_montanha)\n",
528 | "trave_vermelha = AnyNode(nome = \"Trave vermelha\", cargo = \"Soldado\", parent = dep_mestre_montanha)\n",
529 | "sandalia_de_palha = AnyNode(nome = \"Sandália de Palha\", cargo = \"Chefe de comunicações\", parent = dep_mestre_montanha)\n",
530 | "os49 = AnyNode(nome = \"49'ers o(s) 49\", cargo = \"Membros comuns\", parent = trave_vermelha)\n",
531 | "lanternas_azuis = AnyNode(nome = \"Lanternas azuis\", cargo = \"Membros ainda não iniciados\", parent = trave_vermelha)\n",
532 | "\n",
533 | "print(RenderTree(dragon_head))"
534 | ]
535 | },
536 | {
537 | "cell_type": "markdown",
538 | "metadata": {
539 | "colab_type": "text",
540 | "id": "P42blwaujUeP"
541 | },
542 | "source": [
543 | "### Exercício 4:"
544 | ]
545 | },
546 | {
547 | "cell_type": "code",
548 | "execution_count": null,
549 | "metadata": {
550 | "colab": {
551 | "base_uri": "https://localhost:8080/",
552 | "height": 367
553 | },
554 | "colab_type": "code",
555 | "id": "mC1H3fZdi_hC",
556 | "outputId": "9e6c1394-ed57-42c3-dd64-cbe621fb11f1"
557 | },
558 | "outputs": [],
559 | "source": [
560 | "from anytree import Node,AnyNode, RenderTree\n",
561 | "\n",
562 | "RPMTI = AnyNode(desc = \"Resoluções e Problemas Matemáticos para Tecnologia da Informação\", car_horaria = \"180h\")\n",
563 | "PLEI = AnyNode(desc = \"Práticas de leitura e escrita I\", carg_horaria = \"30h\")\n",
564 | "PLI = AnyNode(desc = \"Práticas de leitura em inglês\", carg_horaria = \"30h\")\n",
565 | "TIS = AnyNode(desc = \"Tecnologia da infromação e socidade\", carg_horaria = \"30h\")\n",
566 | "CI = AnyNode(desc = \"Cálculo diferencial e integral I\", car_horaria = \"90h\", parent = RPMTI)\n",
567 | "ITP = AnyNode(desc = \"Introdução as Técnicas de Programação\", car_horaria = \"60h\", parent = RPMTI)\n",
568 | "PTP = AnyNode(desc = \"prática de Técnicas de Programação\", car_horaria = \"30h\", parent = RPMTI)\n",
569 | "VGA = AnyNode(desc = \"Vetores e Geometria Análita\", car_horaria = \"60h\", parent = RPMTI)\n",
570 | "FMCI = AnyNode(desc = \"Fundamentos matemáticos da computação I\", car_horaria = \"90h\", parent = RPMTI)\n",
571 | "PLEII = AnyNode(desc = \"Práticas de leitura e escrita II\", carg_horaria = \"30h\", parent = PLEI)\n",
572 | "ALC = AnyNode(desc = \"Àlgebra Linear para computação\", carg_horaria = \"60h\", parent = VGA)\n",
573 | "MEII = AnyNode(desc = \"Matemática para engenharia II\", carg_horaria = \"90h\", parent = CI)\n",
574 | "PF = AnyNode(desc = \"Programação Funcional\", carg_horaria = \"60h\", parent = RPMTI)\n",
575 | "FMCII = AnyNode(desc = \"Fundamentos matemáticos da computação II\", carg_horaria = \"90h\", parent = FMCI)\n",
576 | "MEIII = AnyNode(desc = \"Matemática para engenharia III\", carg_horaria = \"90h\", parent = MEII)\n",
577 | "FMCIII = AnyNode(desc = \"Fundamentos matemáticos da computação III\", carg_horaria = \"90h\", parent = FMCII)\n",
578 | "\n",
579 | "print(RenderTree(RPMTI),RenderTree(PLEI),RenderTree(PLI),RenderTree(TIS))"
580 | ]
581 | }
582 | ],
583 | "metadata": {
584 | "colab": {
585 | "collapsed_sections": [],
586 | "name": "Tree_v2.ipynb",
587 | "provenance": [],
588 | "version": "0.3.2"
589 | },
590 | "kernelspec": {
591 | "display_name": "Python 3",
592 | "language": "python",
593 | "name": "python3"
594 | },
595 | "language_info": {
596 | "codemirror_mode": {
597 | "name": "ipython",
598 | "version": 3
599 | },
600 | "file_extension": ".py",
601 | "mimetype": "text/x-python",
602 | "name": "python",
603 | "nbconvert_exporter": "python",
604 | "pygments_lexer": "ipython3",
605 | "version": "3.6.8"
606 | }
607 | },
608 | "nbformat": 4,
609 | "nbformat_minor": 1
610 | }
611 |
--------------------------------------------------------------------------------