\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{Fide (fidelp27)} \pdfinfo{ /Title (set-conjuntos-en-python.pdf) /Creator (Cheatography) /Author (Fide (fidelp27)) /Subject (Set - Conjuntos (en Python) Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{0C6901} \definecolor{LightBackground}{HTML}{F7FAF7} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Set - Conjuntos (en Python) Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{Fide (fidelp27)} via \textcolor{DarkBackground}{\uline{cheatography.com/175090/cs/37053/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}Fide (fidelp27) \\ \uline{cheatography.com/fidelp27} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Published 12th February, 2023.\\ Updated 12th February, 2023.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{¿Qué es un conjunto?}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{Un conjunto en Python es una colección no ordenada de elementos únicos.} \tn % Row Count 2 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{8.635 cm} x{8.635 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Usos de conjuntos}} \tn % Row 0 \SetRowColor{LightBackground} Eliminación de elementos duplicados: Si tienes una lista con elementos repetidos y quieres quitar los duplicados, puedes crear un conjunto a partir de esa lista y luego volver a convertirla en una lista. & Verificación de pertenencia: Puedes utilizar un conjunto para verificar si un elemento específico pertenece a una colección o no. Esto es más rápido que verificar manualmente si un elemento está en una lista o en otro tipo de colección. \tn % Row Count 13 (+ 13) % Row 1 \SetRowColor{white} Cálculo de intersecciones y diferencias: Si tienes dos o más conjuntos y quieres encontrar la intersección (elementos en común) o la diferencia (elementos exclusivos) entre ellos, puedes utilizar los métodos de intersección y diferencia de los conjuntos. & Análisis de datos: Los conjuntos son útiles en el análisis de datos para realizar operaciones como contar la frecuencia de elementos en una colección o encontrar valores únicos. \tn % Row Count 26 (+ 13) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{8.635 cm} x{8.635 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Creación de conjuntos}} \tn % Row 0 \SetRowColor{LightBackground} 1) Para crear un conjunto especificamos sus elementos entre llaves & 2) Puede contener distintos tipos de datos, excepto objetos inmutables \tn % Row Count 4 (+ 4) % Row 1 \SetRowColor{white} 3) Python diferencia diccionarios de objetos por uso de ":" para separar keys y values. Sin embargo la no reconoce la creación de conjuntos con la notación de "\{\}" directamente & 4) Un set puede ser convertido a una lista y viceversa. \tn % Row Count 13 (+ 9) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Ejemplos con código}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\#1 Creación de conjuntos \newline conjunto = \{1, 2, 3, 4\} \newline \newline \#2 Contiene diversos tipos \newline conjunto = s = \{2.16, False, True, "string", (1, 2)\} \newline \newline \#Excepto objetos mutables \newline conjunto = \{{[}a, b, c{]}\} -\textgreater{} TypeError: unhashable type: 'list' \newline \newline \#3 Python diferencia conjuntos de colecciones \newline conjunto = \{\} -\textgreater{} colección \newline conjunto = set() -\textgreater{} conjunto \newline \newline \#4 Se pueden convertir conjuntos a listas y viceversa \newline list(\{1, 2 ,3 ,4, 5\}) -\textgreater{} output: {[}1,2,3,4,5{]} \newline \newline set({[}1, 2, 2, 3, 4, 4, 5, 6{]}) -\textgreater{} output: \{1,2,3,4,5,6\} (sin repetidos)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Métodos para agregar elementos}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\#add: agrega un elemento al conjunto. \newline conjunto = set() \newline conjunto.add(1) -\textgreater{} output: \{1\} \newline \newline \#update: agrega varios elementos al conjunto. \newline conjunto = set({[}1, 2, 3{]}) \newline conjunto.update({[}3, 4, 5{]}) -\textgreater{} output: \{1, 2, 3, 4, 5\}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Métodos para eliminar elementos}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\#remove: elimina un elemento específico del conjunto. \newline conjunto = set({[}1, 2, 3, 4, 5{]}) \newline conjunto.remove(3) -\textgreater{} \{1, 2, 4, 5\} \newline \newline \#discard: elimina un elemento específico del conjunto, pero no produce un error si el elemento no está en el conjunto. \newline conjunto = set({[}1, 2, 3, 4, 5{]}) \newline conjunto.discard(6) \# no produce un error -\textgreater{} output: \{1, 2, 3, 4, 5\} \newline \newline \#pop: elimina y devuelve un elemento arbitrario del conjunto. \newline conjunto = set({[}1, 2, 3, 4, 5{]}) \newline print(conjunto.pop()) \# imprime un elemento arbitrario, por ejemplo: 1 -\textgreater{} output: \{2, 3, 4, 5\} \newline \newline \#clear: elimina todos los elementos del conjunto. \newline conjunto = set({[}1, 2, 3, 4, 5{]}) \newline conjunto.clear() -\textgreater{} output: set()} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Métodos de verificación}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\#issubset: verifica si un conjunto es un subconjunto de otro conjunto. Verifica que todos los elementos de "a" están presentes en el conjunto "b" \newline \newline conjunto\_a = set({[}1, 2, 3{]}) \newline conjunto\_b = set({[}1, 2, 3, 4, 5{]}) \newline print(conjunto\_a.issubset(conjunto\_b)) -\textgreater{} output: True \newline \newline \newline \#issuperset: verifica si un conjunto es un superconjunto de otro conjunto. Si todos los elementos del conjunto "b" están presentes en el conjunto "a" \newline \newline conjunto\_a = set({[}1, 2, 3, 4, 5{]}) \newline conjunto\_b = set({[}1, 2, 3{]}) \newline print(conjunto\_a.issuperset(conjunto\_b)) -\textgreater{} output: True \newline \newline \#isdisjoint: verifica si dos conjuntos no tienen elementos en común. \newline \newline conjunto\_a = set({[}1, 2, 3{]}) \newline conjunto\_b = set({[}4, 5, 6{]}) \newline print(conjunto\_a.isdisjoint(conjunto\_b)) -\textgreater{} output: True} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Métodos de operación}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\#union: devuelve un conjunto que contiene los elementos de ambos conjuntos. \newline \newline conjuntoA = \{1, 2, 3, 4\} \newline conjuntoB = \{3, 4, 5, 6\} \newline conjuntoC = \seqsplit{conjuntoA.union(conjuntoB)} ó conjuntoC = conjuntoA | conjuntoB \newline -\textgreater{} output: \{1, 2, 3, 4, 5\} \newline \newline \#intersection: devuelve un conjunto que contiene los elementos en común entre dos conjuntos. \newline \newline conjuntoA = \{1, 2, 3, 4\} \newline conjuntoB = \{3, 4, 5, 6\} \newline conjuntoC = \seqsplit{conjuntoA.intersection(conjuntoB)} ó conjuntoC = conjuntoA \& conjuntoB \newline -\textgreater{} output: \{3,4\} \newline \newline \#difference: devuelve un conjunto que contiene los elementos exclusivos de un conjunto en comparación con otro. Elementos únicos en A que no contiene B \newline \newline conjuntoA = \{1, 2, 3, 4\} \newline conjuntoB = \{3, 4, 5, 6\} \newline conjuntoC = \seqsplit{conjuntoA.difference(conjuntoB)} ó conjuntoC = conjuntoA - conjuntoB \newline -\textgreater{} output: \{1,2\} \newline \newline \#symmetric\_difference: devuelve un conjunto que contiene los elementos que no están en común entre dos conjuntos. Elementos únicos en A al comparar con B y viceversa \newline \newline conjuntoA = \{1, 2, 3, 4\} \newline conjuntoB = \{3, 4, 5, 6\} \newline conjuntoC = \seqsplit{conjuntoA.symmetric\_difference(conjuntoB)} ó conjuntoC = conjuntoA \textasciicircum{} conjuntoB \newline -\textgreater{} output: \{1,2,5,6\} \newline \newline \#update: es una operación que permite modificar un conjunto existente agregándole elementos de otro conjunto. Modifica directamente el conjunto A a diferencia de la unión que crea un nuevo conjunto \newline \newline conjuntoA = \{1, 2, 3, 4\} \newline conjuntoB = \{3, 4, 5, 6\} \newline conjuntoA.update(conjuntoB) ó conjuntoA |= conjuntoB \newline -\textgreater{} output: \{1,2,3,4,5,6\}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \end{document}