create account

Curso Intermedio de Python N03 Conjuntos by rafaelaquino

View this thread on: hive.blogpeakd.comecency.com
· @rafaelaquino ·
$2.23
Curso Intermedio de Python N03 Conjuntos
Cordiales Saludos

<center>
![caractula03.png](https://files.peakd.com/file/peakd-hive/rafaelaquino/23uR9nP9MBmdK1pLJqBiwnkoFPy8hjMTMz9JbkysVkT7TEx5S3mrsB1G61oTFQBDa5SVg.png)
</center>
#### Conjuntos

Un conjunto es una colección de elementos los cuales se pueden modificar, estos elementos no manejan ningún orden (están desordenados) y no acepta duplicados. Los elementos los agrupamos dentro de **{ }** al momento de declararlos o crearlos.


##### Declaración o Creación de conjuntos
~~~
>>> colores = {'azul','rojo', 'amarillo'}
>>> colores
{'amarillo', 'azul', 'rojo'}
~~~


##### type( ), dir( )
~~~
>>> type(colores)
<class 'set'>

>>> dir(colores)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
>>>
~~~

### Otras formas de declarar o crear conjuntos

Conjunto a partir de una lista
~~~
>>> conjunto_lista = set([1,2,3,4,5,])
>>> conjunto_lista
{1, 2, 3, 4, 5}
>>> type(conjunto_lista)
<class 'set'>
~~~

Conjunto a partir de una tupla
~~~
>>> conjunto_tupla = set((100,200,300,400))
>>> conjunto_tupla
{200, 100, 400, 300}
~~~

Conjunto a partir de un string

~~~
>>> cadena_texto = set('Rafael')
>>> cadena_texto
{'f', 'l', 'e', 'a', 'R'}
>>> type(cadena_texto)
<class 'set'>
~~~

Creando un Conjunto vacio
~~~
>>> conjunto_vacio = set()
>>> conjunto_vacio
set()
>>> type(conjunto_vacio)
<class 'set'>
>>> 

~~~

Conjunto a partir de un rango

~~~
>>> conj_rango = set(range(5))
>>> conj_rango
{0, 1, 2, 3, 4}
>>> type(conj_rango)
<class 'set'>
>>> 

~~~


#### Métodos
##### .add : Agregar Elementos a un conjunto 

Teniendo el conjunto: **conj_rango**, previamente creado le vamos a agregar un nuevo elemento. En este caso el número 100, para esta operación utilizamos el método **.add**.
~~~
>>> conj_rango
{0, 1, 2, 3, 4}
>>> conj_rango.add(100)
>>> conj_rango
{0, 1, 2, 3, 4, 100}
>>> 

~~~

##### .update : Agregar Elementos Iterables
Update lo utilizaremos para agregar más de un elemento, es decir varios elementos con una sola operación.


Actualización del conjunto con **lista**
~~~
>>> lista = [5,6,7,8]
>>> conj_rango.update(lista)
>>> conj_rango
{0, 1, 2, 3, 4, 100, 5, 6, 7, 8}
~~~

Actuializacion del conjunto con **tupla**
~~~
>>> tupla = (9,10,11)
>>> conj_rango.update(tupla)
>>> conj_rango
{0, 1, 2, 3, 4, 100, 5, 6, 7, 8, 9, 10, 11}
~~~

Actualización del conjunto con **range**

~~~
>>> rango = range(12,15)
>>> conj_rango.update(rango)
>>> conj_rango
{0, 1, 2, 3, 4, 100, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}

~~~
##### .discard(): Permite eliminar un elemento.
PRIMER CASO. Si el elemento existe. En este caso eliminaremos el número **100**, Al existir en el conjunto lo elimina automáticamente.
~~~
conj_rango
{0, 1, 2, 3, 4, 100, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
>>> conj_rango.discard(100)
>>> conj_rango
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
~~~

SEGUNDO CASO. Si el elemento no existe. En este caso eliminaremos el número **20** con la instrucción: conj_rango.discard(20). Al realizar el proceso como no existe el número **20**, no realiza la eliminación y **no da error**.
~~~
>>> conj_rango
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
>>> conj_rango.discard(20)
>>> conj_rango
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}

~~~

##### .remove(): Elimina un elemento del conjunto

PRIMER CASO. Si el elemento existe lo elimina automáticamente. En este caso eliminaremos el número **0**, existente en: **conj_rango**
~~~
>>> conj_rango
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
>>> conj_rango.remove(0)
>>> conj_rango
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
~~~
SEGUNDO CASO. Si el elemento no existe. En este caso eliminaremos el número 15 con la instrucción: conj_rango.remove(15). Al realizar el proceso como el número **15** no existe en el conjunto python nos lanza un error de tipo **KeyError**.

~~~
>>> conj_rango
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
>>> conj_rango.remove(15)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 15
~~~

##### .pop(): Elimina un elemento de forma aleatoria. En este caso al ejecutar: **conj_rango.pop()** se eliminó el elemento: **1** (De forma aleatoria)
~~~
>>> conj_rango
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
>>> conj_rango.pop()
1
>>> conj_rango
{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}

~~~


##### .clear(): Permite eliminar todos los elementos del conjunto.
~~~
>>> conj_rango
{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
>>> conj_rango.clear()
>>> conj_rango
set()
>>> 

~~~

---

Queda pendiente para la próxima publicación: Operaciones con conjuntos.

Para revisar las publicaciones anteriores del **Curso Intermedio de Python** entra al siguiente link: https://siraquino.github.io/pythoncumanes/intermediopython.html

---

## Profundizando en python

Podemos Ejecutar líneas de códigos directamente desde nuestra terminal:

~~~
rafael@HP:~$ 
rafael@HP:~$ python3 -c 'print("Mensaje Python")'
Mensaje Python
rafael@HP:~$ 
rafael@HP:~$ 
~~~

#### Ejercicio:
Ejecutar desde la terminal una instrucción de python donde se muestre el Zen de Python. Se debe redireccionar la salida del Zen de Python a un archivo de texto denominado zen.txt y mostrarlo con el comando **cat**.

Respuesta:
~~~
rafael@HP:~$ python3 -c 'import this' > zen.txt; cat zen.txt
~~~

~~~
rafael@HP:~$ 
rafael@HP:~$ python3 -c 'import this' > zen.txt; cat zen.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
rafael@HP:~$ 
rafael@HP:~$ 

~~~
Este ejercicio lo coloqué en mi Twitter. Aquí lo muestro.


https://twitter.com/Rafa_elaquino/status/1635672136110026754?s=20

---


#### Invitación
Te invito a que sigas mi curso de **linux**. En este curso Intermedio de Python trabajaremos con este sistema operativo. 
Link: https://siraquino.github.io/pythoncumanes/linux.html 

---


Recurso para aprender Python

[Curso Gratis de Programación](https://siraquino.github.io/pythoncumanes/)
[Curso de Programación Básica](https://siraquino.github.io/pythoncumanes/programacionbasica.html)


---

[Mi Twitter](https://twitter.com/Rafa_elaquino)
[Mi facebook](https://www.facebook.com/rafael.aquino.5815)
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 183 others
properties (23)
authorrafaelaquino
permlinkcurso-intermedio-de-python-n03-conjuntos
categoryhive-154226
json_metadata{"app":"peakd/2023.7.1","format":"markdown","tags":["developspanish","stem-espanol","stemsocial","linux","python","original-content","developer","spanish","tecnologia","programador"],"users":[],"image":["https://files.peakd.com/file/peakd-hive/rafaelaquino/23uR9nP9MBmdK1pLJqBiwnkoFPy8hjMTMz9JbkysVkT7TEx5S3mrsB1G61oTFQBDa5SVg.png"]}
created2023-07-19 16:29:27
last_update2023-07-19 16:29:27
depth0
children2
last_payout2023-07-26 16:29:27
cashout_time1969-12-31 23:59:59
total_payout_value1.134 HBD
curator_payout_value1.092 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,541
author_reputation109,075,590,980,629
root_title"Curso Intermedio de Python N03 Conjuntos"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id125,458,133
net_rshares4,774,221,525,724
author_curate_reward""
vote details (247)
@stemsocial ·
re-rafaelaquino-curso-intermedio-de-python-n03-conjuntos-20230720t022026494z
<div class='text-justify'> <div class='pull-left'>
 <img src='https://stem.openhive.network/images/stemsocialsupport7.png'> </div>

Thanks for your contribution to the <a href='/trending/hive-196387'>STEMsocial community</a>. Feel free to join us on <a href='https://discord.gg/9c7pKVD'>discord</a> to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.&nbsp;<br />&nbsp;<br />
</div>
properties (22)
authorstemsocial
permlinkre-rafaelaquino-curso-intermedio-de-python-n03-conjuntos-20230720t022026494z
categoryhive-154226
json_metadata{"app":"STEMsocial"}
created2023-07-20 02:20:27
last_update2023-07-20 02:20:27
depth1
children0
last_payout2023-07-27 02:20:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length565
author_reputation22,903,677,158,169
root_title"Curso Intermedio de Python N03 Conjuntos"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id125,470,849
net_rshares0
@visualblock ·
<center>

![](https://images.ecency.com/DQmeUXCY8732hkoJpZcnSxQD7NbHUbhe9d8wKYmqN3rN56e/testigo_hispapro.png)

<sup>
Has sido curado por @visualblock / You've been curated by @visualblock 
Bienvenidas delegaciones / Delegations welcome
 [Encuentra nuestra comunidad aquí / Find our community here](https://discord.gg/tGuctbfYKN) 
[Trail de Curación / Curation Trail](https://hive.vote/dash.php?trail=visualblock&i=1)

[Vota por nuestro Testigo aliado - @hispapro](https://vote.hive.uno/@hispapro) / [Vote for our allied Witness - @hispapro](https://vote.hive.uno/@hispapro) 
[Más información sobre el testigo aquí](https://ecency.com/hive-111111/@hispapro/witness-announcement-descubre-el-nuevo) / [More information about the witness here](https://ecency.com/hive-111111/@hispapro/witness-announcement-descubre-el-nuevo)

</sup>

</center>
properties (22)
authorvisualblock
permlinkre-rafaelaquino-2023719t171038497z
categoryhive-154226
json_metadata{"tags":["developspanish","stem-espanol","stemsocial","linux","python","original-content","developer","spanish","tecnologia","programador"],"app":"ecency/3.0.35-vision","format":"markdown+html"}
created2023-07-19 22:10:39
last_update2023-07-19 22:10:39
depth1
children0
last_payout2023-07-26 22:10:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length839
author_reputation152,603,008,711,740
root_title"Curso Intermedio de Python N03 Conjuntos"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id125,466,243
net_rshares0