Skip to content

Commit

Permalink
Dictionaries adventure
Browse files Browse the repository at this point in the history
  • Loading branch information
Ignacio Avas committed May 3, 2017
1 parent dac6dec commit ed385e1
Show file tree
Hide file tree
Showing 5 changed files with 180 additions and 14 deletions.
81 changes: 76 additions & 5 deletions py101/dictionaries/README.es.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,85 @@
Boilerplate
-----------
Diccionarios
------------

Insertar alguna introducción aquí.
Un diccionario es un tipo de datos similar a las listas, pero funciona
asociando claves y valores en en vez de usar índices. Cada valor del
diccionario puede ser accedido usando una clave que puede ser cualquier tipo
de objeto. Por ejemplo se pueden usar cadenas para referenciar objetos del
diccionario. Una pequeña base de datos telefónica puede ser almacenada usando
diccionarios de la siguiente manera

.. sourcecode:: python

print('Some python code here')
directorio = {}
directorio["Alex"] = '2203-3434'
directorio["Rick"] = '+543 3232320'
directorio["Rolling"] = '9476-62781'

De manera alternativa, un diccionario puede ser inicializado usando la
siguiente notación

.. sourcecode:: python

edades = {
'Alex': 23,
'Rick': 42,
'Rolling' : "No lo sé"
}

Iteración
---------

Los diccionarios permiten ser iterados. Para iterar sobre las claves del
diccionario se usa la siguiente sintaxis.

.. sourcecode:: python

for name in ages:
print("Edad de {{}} es {{}}".format(name, ages[name]))

El ejemplo va a imprimir algo similar a:

.. sourcecode::

Edad de Rick es 42
Edad de Rolling es No lo sé
Edad de Alex es 23

Sin embargo, un diccionario no mantiene el orden de los elementos almacenado
en él.

Borrado de claves
-----------------

Para borrar un índice específico usa la palabra clave "del" como se muestra
en el siguiente ejemplo:

.. sourcecode:: python

ages = {
'Alex': 39,
'Rick': 42,
'Rolling' : "I don't know"
}
del ages['Rolling']
print(ages) # imprime {'Rick': 42, 'Alex': 39}


Desafío
-------

Describir el desafío aquí.
Modifica el programa provisto abajo para que la función
"print_only_even_keys", imprima solamente los nombres de aquellas claves
cuyos valores son números pares.

.. sourcecode:: python

def print_only_even_keys(some_dict):
# pon tu código aquí
pass

# no modifiques este código
print_only_even_keys({ 'Alfred': 28, 'Mary': 29 })
print_only_even_keys({ 'Alfred': 31, 'Mary': 29 })


78 changes: 74 additions & 4 deletions py101/dictionaries/README.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,84 @@
Boilerplate
Dictonaries
-----------

Insert some introduction here.
A dictionary is a data type similar to lists, but works with keys and
values instead of indexes. Each value stored in a dictionary can be accessed
using a key, which is any type of object, for example strings
instead of using its index to address it.

For example, a database of phone numbers could be stored using a dictionary
like this:

.. sourcecode:: python

phonebook = {}
phonebook["Alex"] = '2203-3434'
phonebook["Rick"] = '+543 3232320'
phonebook["Rolling"] = '9476-62781'

Alternatively, a dictionary can be initialized using the following notation:

.. sourcecode:: python

ages = {
'Alex': 23,
'Rick': 42,
'Rolling' : "I don't know"
}

Iteration
---------

Dictionaries can be iterated over. To iterate over the dictionary keys, use
the following syntax:

.. sourcecode:: python

for name in ages:
print("Age of {{}} is {{}}".format(name, ages[name]))

The previous example will print something similar to

.. sourcecode::

Age of Rick is 42
Age of Rolling is I don't know
Age of Alex is 23

However, a dictionary, unlike a list, does not keep the order of the values
stored in it.

Key removal
-----------

To remove a specified index, use the "del" keyword as shown in the following
example:

.. sourcecode:: python

print('Some python code here')
ages = {
'Alex': 39,
'Rick': 42,
'Rolling' : "I don't know"
}
del ages['Rolling']
print(ages) # prints {'Rick': 42, 'Alex': 39}


Challenge
---------

Describe the challenge here
Modify the program below, so the "print_only_even_keys" function prints
only the name of the keys whose values are even numbers

.. sourcecode:: python

def print_only_even_keys(some_dict):
# put your code here
pass

# Don't modify this code
print_only_even_keys({ 'Alfred': 28, 'Mary': 29 })
print_only_even_keys({ 'Alfred': 31, 'María': 29 })

The program should Output "Alfred" in the first line and nothing else
8 changes: 7 additions & 1 deletion py101/dictionaries/SOLUTION.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
.. sourcecode:: python

print('Some solution here')
def print_only_even_keys(some_dict):
for key in some_dict:
if some_dict[key] % 2 == 0:
print(key)

print_only_even_keys({ 'Alfred': 28, 'Mary': 29 })
print_only_even_keys({ 'Alfred': 31, 'Mary': 29 })
15 changes: 11 additions & 4 deletions py101/dictionaries/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,17 @@ def tearDown(self):
def runTest(self):
"""Makes a simple test of the output"""

# code = compile(self.candidate_code, self.file_name, 'exec',
# optimize=0)
# exec(code)
self.fail("Test not implemented")

code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)

self.assertIn('print_only_even_keys',
code.co_names,
'Should have the print_only_even_keys function defined')
eval(code)

self.assertMultiLineEqual("Alfred\n",
self.__mockstdout.getvalue(),
"Should have the same output")


class Adventure(BaseAdventure):
Expand Down
12 changes: 12 additions & 0 deletions tests/test_story.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import py101.loops
import py101.functions
import py101.classes
import py101.dictionaries
import unittest


Expand Down Expand Up @@ -101,6 +102,17 @@ def description(self):
print(car1.description())
print(car2.description())"""
),
AdventureData(
py101.dictionaries,
"""def print_only_even_keys(some_dict):
for key in some_dict:
if some_dict[key] % 2 == 0:
print(key)
print_only_even_keys({ 'Alfred': 28, 'Mary': 29 })
print_only_even_keys({ 'Alfred': 31, 'Mary': 29 })
"""
)
]

Expand Down

0 comments on commit ed385e1

Please sign in to comment.