Skip to content
Snippets Groups Projects
Commit 08e8313a authored by Omar Asto Rojas's avatar Omar Asto Rojas
Browse files

Primer adelanto de tarea.

parent 405d62cc
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## TAREA 2
# Asto Rojas, Omar
%% Cell type:markdown id: tags:
Programa en Python que te permite ingresar una lista de palabras
separadas por guión para despúes ordenarlas alfabéticamente,
conservando el mismo formato de entrada.
%% Cell type:code id: tags:
``` python
def Ordenar_lista(a):
"""
Función que te permite ordenar una lista que tiene palabras separadas por guiones.
Debes itroducir una lista de la siguiente forma: ["word1-word2-word3"]
"""
#Esta línea crea una lista a partir de la introducida donde sus elementos
#son los que estaban seprados por guiones.
newlist1 = [word for line in a for word in line.split("-")]
#En esta línea primero se utiliza la función set para eliminar los elemntos iguales.
#Despúes con la función sorted se ordena la lista.
newlist2 = sorted(set(newlist1))
#En esta línea se crea un conjunto de palabras donde cada una es separada por un guión
#como en el inicio
newlist3 = '-'.join(newlist2)
print(a, newlist1, newlist2, newlist3)
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## Triángulo de Pascal
### Asto Rojas, Omar
Programa que te permite obtener un elemento determinado
del triángulo de Pascal.
%% Cell type:code id: tags:
``` python
def Pascal(n):
"""
El código solo corre si el número entregado es entero,
el comando if y la función isinstance(#, naturaleza de #)
permiten esto.
"""
if isinstance(n, int):
list=[1] ##una vez cumplida la condición, se crea una lista con el elemento 1
for i in range(n-1): ##recorre desde 0 al # que le entregemos
newlist=[] ## se crea otra lista
newlist.append(list[0]) ##en la nueva lista, se agrega el primer elemento de list
for i in range(len(list)-1): ## este for depende de la medida de list
newlist.append(list[i]+list[i+1]) ## hace que se agrege a la nueva lista la suma de un elemnto de list con el siguiente
newlist.append(list[-1]) ##agregas el último
list=newlist #aqué se reemplaza a la nueva lista por la nueva, para volver a la iteración
print(list)
if isinstance(n, float):
return "introduzca_un_entero"
else:
print("introduce un número")
```
%% Cell type:code id: tags:
``` python
Pascal("a")
```
%% Cell type:markdown id: tags:
## Segunda parte del ejercicio:
%% Cell type:code id: tags:
``` python
def Pascal2(nums):
"""
Esta primera parte del ejercicio solo toma los enteros introducidos en la lista.
"""
new_list = []
for value in nums:
new_list.append(str(value))
new = [x for x in new_list if x.isdigit()]
final = []
for value in new:
final.append(int(value))
"""
*******************************
Segunda parte, en donde se modifica el código del primer ejercicio.
"""
real_final = []
for value in final:
lists=[1]
for i in range(value):
newlist2=[]
newlist2.append(lists[0])
for i in range(len(lists)-1):
newlist2.append(lists[i]+lists[i+1])
newlist2.append(lists[-1])
lists=newlist2
real_final.append(lists)
print(real_final)
result = []
for sublist in real_final:
for item in sublist:
result.append(item)
print(result)
```
%% Cell type:code id: tags:
``` python
Pascal2([2,4])
```
%% Output
[[1, 2, 1], [1, 4, 6, 4, 1]]
[1, 2, 1, 1, 4, 6, 4, 1]
%% Cell type:markdown id: tags:
## Amigos congueros
### Asto Rojas, Omar
%% Cell type:code id: tags:
``` python
Amig_Cong = {"andreatugores" : {"Nombre" : "Andrea Carolina","Apellido" : "Tugores Hernádez", "Edad" : 24, "País" : "Venezuela", "Residencia" : "Caracas", "Especialidad" : "Física médica", "Institución" : "UCV" , "Hobbie" : "tennis" },
"arturos" : {"Nombre" : "Arturo","Apellido" : "Sanchez", "Edad" : 34, "País" : "Venezuela", "Residencia" : "Ginebra", "Especialidad" : "Física", "Institución" : "LAPP" , "Hobbie" : "montar bicicleta" },
"grisalesj" : {"Nombre" : "Jennifer","Apellido" : "Grisales", "Edad" : 27, "País" : "Colombia", "Residencia" : "Bucaramanga", "Especialidad" : "Física", "Institución" : "UIS" , "Hobbie" : "rugby" },
"hernandezj" : {"Nombre" : "Juan David","Apellido" : "Hernandez", "Edad" : 24, "País" : "Colombia", "Residencia" : "Bógota", "Especialidad" : "Electrodinámica Cuántica", "Institución" : "UNC" , "Hobbie" : "leer y jugar en el computador" },
"jal" : {"Nombre" : "José Antonio", "Apellido" : "López", "Edad" : 50, "País" : "Venezuela", "Residencia" : "", "Especialidad" : "Física", "Institución" : "UCV" , "Hobbie" : "excursionismo, cocinar, leer." },
"martinezj" : {"Nombre" : "Jocabed","Apellido" : "Martinez", "Edad" : 22, "País" : "Venezuela", "Residencia" : "Caracas", "Especialidad" : "", "Institución" : "UCV" , "Hobbie" : "música" },
"ramosm" : {"Nombre" : "María","Apellido" : "Ramos", "Edad" : 23, "País" : "Venezuela", "Residencia" : "Mérida", "Especialidad" : "", "Institución" : "UA" , "Hobbie" : "escribir" },
"vargass" : {"Nombre" : "Sasiri Juliana", "Apellido" : "Vargas Urbano", "Edad" : 20, "País" : "Colombia", "Especialidad" : "Física estadística", "Institución" : "Univalle" , "Hobbie" : "cantar, bailar y tacar instrumentos musicales: guitarra y flauta traversa." },
"cristian.velandia" : {"Nombre" : "Cristian","Apellido" : "Velandia", "Edad" : 27, "País" : "Colombia", "Residencia": "Colombia", "Especialidad" : "Óptica", "Institución" : "UNC" , "Hobbie" : "ánime y videojuegos" },
"ramosd" : {"Nombre" : "David","Apellido" : "Ramos", "Edad" : 24, "País" : "Colombia", "Residencia" : "Bucaramanga", "Especialidad" : "Astrofísica relativista", "Institución" : "UIS" , "Hobbie" : "tocar guitarra" }}
```
%% Cell type:code id: tags:
``` python
Amig_Cong["andreatugores"]
```
%% Output
{'Nombre': 'Andrea Carolina',
'Apellido': 'Tugores Hernádez',
'Edad': 24,
'País': 'Venezuela',
'Residencia': 'Caracas',
'Especialidad': 'Física médica',
'Institución': 'UCV',
'Hobbie': 'tennis'}
%% Cell type:code id: tags:
``` python
def sum_math_v_vi_average(list_of_dicts, Nom_pais):
for d in list_of_dicts:
n1 = d.pop('V')
n2 = d.pop('VI')
d['V+VI'] = (n1 + n2)/2
return list_of_dicts
student_details= [
{'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82},
{'id' : 2, 'subject' : 'math', 'V' : 73, 'VI' : 74},
{'id' : 3, 'subject' : 'math', 'V' : 75, 'VI' : 86}
]
print(sum_math_v_vi_average(student_details, Nom_pais)
```
%% Output
File "<ipython-input-41-914f065b3643>", line 12
print(sum_math_v_vi_average(student_details)
^
SyntaxError: unexpected EOF while parsing
%% Cell type:code id: tags:
``` python
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
while True:
try:
print(f'Dictionary length: {len(a_dict)}')
item = a_dict.popitem()
# Do something with item here...
print(f'{item} removed')
except KeyError:
print('The dictionary has no item now...')
break
```
%% Output
Dictionary length: 3
('pet', 'dog') removed
Dictionary length: 2
('fruit', 'apple') removed
Dictionary length: 1
('color', 'blue') removed
Dictionary length: 0
The dictionary has no item now...
%% Cell type:code id: tags:
``` python
def test(dictt,keys):
return [list(d[k] for k in keys) for d in dictt]
```
%% Cell type:code id: tags:
``` python
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-56-ef963dc32de9> in <module>
----> 1 test(Amig_Cong,["País"])
<ipython-input-46-bddd753df120> in test(dictt, keys)
1 def test(dictt,keys):
----> 2 return [list(d[k] for k in keys) for d in dictt]
<ipython-input-46-bddd753df120> in <listcomp>(.0)
1 def test(dictt,keys):
----> 2 return [list(d[k] for k in keys) for d in dictt]
<ipython-input-46-bddd753df120> in <genexpr>(.0)
1 def test(dictt,keys):
----> 2 return [list(d[k] for k in keys) for d in dictt]
TypeError: string indices must be integers
%% Cell type:code id: tags:
``` python
students = [
{'student_id': 1, 'name': 'Jean Castro', 'class': 'V'},
{'student_id': 2, 'name': 'Lula Powell', 'class': 'V'},
{'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'},
{'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'},
{'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'}
]
list(students)
```
%% Output
[{'student_id': 1, 'name': 'Jean Castro', 'class': 'V'},
{'student_id': 2, 'name': 'Lula Powell', 'class': 'V'},
{'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'},
{'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'},
{'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'}]
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## Lista de Palabras
# Asto Rojas, Omar
%% Cell type:markdown id: tags:
Programa en Python que te permite ingresar una lista de palabras
separadas por guión para despúes ordenarlas alfabéticamente,
conservando el mismo formato de entrada.
%% Cell type:code id: tags:
``` python
def Ordenar_lista(a):
"""
Función que te permite ordenar una lista que tiene palabras separadas por guiones.
Debes itroducir una lista de la siguiente forma: ["word1-word2-word3"]
"""
#Esta línea crea una lista a partir de la introducida donde sus elementos
#son los que estaban seprados por guiones.
newlist1 = [word for line in a for word in line.split("-")]
#En esta línea primero se utiliza la función set para eliminar los elemntos iguales.
#Despúes con la función sorted se ordena la lista.
newlist2 = sorted(set(newlist1))
#En esta línea se crea un conjunto de palabras donde cada una es separada por un guión
#como en el inicio
newlist3 = '-'.join(newlist2)
print(a, newlist1, newlist2, newlist3)
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## Triángulo de Pascal
### Asto Rojas, Omar
Programa que te permite obtener un elemento determinado
del triángulo de Pascal.
%% Cell type:code id: tags:
``` python
def Pascal(n):
"""
El código solo corre si el número entregado es entero,
el comando if y la función isinstance(#, naturaleza de #)
permiten esto.
"""
if isinstance(n, int):
list=[1] ##una vez cumplida la condición, se crea una lista con el elemento 1
for i in range(n-1): ##recorre desde 0 al # que le entregemos
newlist=[] ## se crea otra lista
newlist.append(list[0]) ##en la nueva lista, se agrega el primer elemento de list
for i in range(len(list)-1): ## este for depende de la medida de list
newlist.append(list[i]+list[i+1]) ## hace que se agrege a la nueva lista la suma de un elemnto de list con el siguiente
newlist.append(list[-1]) ##agregas el último
list=newlist #aqué se reemplaza a la nueva lista por la nueva, para volver a la iteración
print(list)
if isinstance(n, float):
return "introduzca_un_entero"
else:
print("introduce un número")
```
%% Cell type:code id: tags:
``` python
Pascal("a")
```
%% Cell type:markdown id: tags:
## Segunda parte del ejercicio:
%% Cell type:code id: tags:
``` python
def Pascal2(nums):
"""
Esta primera parte del ejercicio solo toma los enteros introducidos en la lista.
"""
new_list = []
for value in nums:
new_list.append(str(value))
new = [x for x in new_list if x.isdigit()]
final = []
for value in new:
final.append(int(value))
"""
*******************************
Segunda parte, en donde se modifica el código del primer ejercicio.
"""
real_final = []
for value in final:
lists=[1]
for i in range(value):
newlist2=[]
newlist2.append(lists[0])
for i in range(len(lists)-1):
newlist2.append(lists[i]+lists[i+1])
newlist2.append(lists[-1])
lists=newlist2
real_final.append(lists)
print(real_final)
result = []
for sublist in real_final:
for item in sublist:
result.append(item)
print(result)
```
%% Cell type:code id: tags:
``` python
Pascal2([2,4])
```
%% Output
[[1, 2, 1], [1, 4, 6, 4, 1]]
[1, 2, 1, 1, 4, 6, 4, 1]
%% Cell type:markdown id: tags:
## Amigos congueros
### Asto Rojas, Omar
%% Cell type:code id: tags:
``` python
Amig_Cong = {"andreatugores" : {"Nombre" : "Andrea Carolina","Apellido" : "Tugores Hernádez", "Edad" : 24, "País" : "Venezuela", "Residencia" : "Caracas", "Especialidad" : "Física médica", "Institución" : "UCV" , "Hobbie" : "tennis" },
"arturos" : {"Nombre" : "Arturo","Apellido" : "Sanchez", "Edad" : 34, "País" : "Venezuela", "Residencia" : "Ginebra", "Especialidad" : "Física", "Institución" : "LAPP" , "Hobbie" : "montar bicicleta" },
"grisalesj" : {"Nombre" : "Jennifer","Apellido" : "Grisales", "Edad" : 27, "País" : "Colombia", "Residencia" : "Bucaramanga", "Especialidad" : "Física", "Institución" : "UIS" , "Hobbie" : "rugby" },
"hernandezj" : {"Nombre" : "Juan David","Apellido" : "Hernandez", "Edad" : 24, "País" : "Colombia", "Residencia" : "Bógota", "Especialidad" : "Electrodinámica Cuántica", "Institución" : "UNC" , "Hobbie" : "leer y jugar en el computador" },
"jal" : {"Nombre" : "José Antonio", "Apellido" : "López", "Edad" : 50, "País" : "Venezuela", "Residencia" : "", "Especialidad" : "Física", "Institución" : "UCV" , "Hobbie" : "excursionismo, cocinar, leer." },
"martinezj" : {"Nombre" : "Jocabed","Apellido" : "Martinez", "Edad" : 22, "País" : "Venezuela", "Residencia" : "Caracas", "Especialidad" : "", "Institución" : "UCV" , "Hobbie" : "música" },
"ramosm" : {"Nombre" : "María","Apellido" : "Ramos", "Edad" : 23, "País" : "Venezuela", "Residencia" : "Mérida", "Especialidad" : "", "Institución" : "UA" , "Hobbie" : "escribir" },
"vargass" : {"Nombre" : "Sasiri Juliana", "Apellido" : "Vargas Urbano", "Edad" : 20, "País" : "Colombia", "Especialidad" : "Física estadística", "Institución" : "Univalle" , "Hobbie" : "cantar, bailar y tacar instrumentos musicales: guitarra y flauta traversa." },
"cristian.velandia" : {"Nombre" : "Cristian","Apellido" : "Velandia", "Edad" : 27, "País" : "Colombia", "Residencia": "Colombia", "Especialidad" : "Óptica", "Institución" : "UNC" , "Hobbie" : "ánime y videojuegos" },
"ramosd" : {"Nombre" : "David","Apellido" : "Ramos", "Edad" : 24, "País" : "Colombia", "Residencia" : "Bucaramanga", "Especialidad" : "Astrofísica relativista", "Institución" : "UIS" , "Hobbie" : "tocar guitarra" }}
```
%% Cell type:code id: tags:
``` python
Amig_Cong["andreatugores"]
```
%% Output
{'Nombre': 'Andrea Carolina',
'Apellido': 'Tugores Hernádez',
'Edad': 24,
'País': 'Venezuela',
'Residencia': 'Caracas',
'Especialidad': 'Física médica',
'Institución': 'UCV',
'Hobbie': 'tennis'}
%% Cell type:code id: tags:
``` python
def sum_math_v_vi_average(list_of_dicts, Nom_pais):
for d in list_of_dicts:
n1 = d.pop('V')
n2 = d.pop('VI')
d['V+VI'] = (n1 + n2)/2
return list_of_dicts
student_details= [
{'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82},
{'id' : 2, 'subject' : 'math', 'V' : 73, 'VI' : 74},
{'id' : 3, 'subject' : 'math', 'V' : 75, 'VI' : 86}
]
print(sum_math_v_vi_average(student_details, Nom_pais)
```
%% Output
File "<ipython-input-41-914f065b3643>", line 12
print(sum_math_v_vi_average(student_details)
^
SyntaxError: unexpected EOF while parsing
%% Cell type:code id: tags:
``` python
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
while True:
try:
print(f'Dictionary length: {len(a_dict)}')
item = a_dict.popitem()
# Do something with item here...
print(f'{item} removed')
except KeyError:
print('The dictionary has no item now...')
break
```
%% Output
Dictionary length: 3
('pet', 'dog') removed
Dictionary length: 2
('fruit', 'apple') removed
Dictionary length: 1
('color', 'blue') removed
Dictionary length: 0
The dictionary has no item now...
%% Cell type:code id: tags:
``` python
def test(dictt,keys):
return [list(d[k] for k in keys) for d in dictt]
```
%% Cell type:code id: tags:
``` python
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-56-ef963dc32de9> in <module>
----> 1 test(Amig_Cong,["País"])
<ipython-input-46-bddd753df120> in test(dictt, keys)
1 def test(dictt,keys):
----> 2 return [list(d[k] for k in keys) for d in dictt]
<ipython-input-46-bddd753df120> in <listcomp>(.0)
1 def test(dictt,keys):
----> 2 return [list(d[k] for k in keys) for d in dictt]
<ipython-input-46-bddd753df120> in <genexpr>(.0)
1 def test(dictt,keys):
----> 2 return [list(d[k] for k in keys) for d in dictt]
TypeError: string indices must be integers
%% Cell type:code id: tags:
``` python
students = [
{'student_id': 1, 'name': 'Jean Castro', 'class': 'V'},
{'student_id': 2, 'name': 'Lula Powell', 'class': 'V'},
{'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'},
{'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'},
{'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'}
]
list(students)
```
%% Output
[{'student_id': 1, 'name': 'Jean Castro', 'class': 'V'},
{'student_id': 2, 'name': 'Lula Powell', 'class': 'V'},
{'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'},
{'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'},
{'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'}]
%% Cell type:code id: tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment