Welcome to the new installment of my series of Coding Quizzes, in which you will be able to test your knowledge and skills about programming and software development in a simple and fun way. If you want to learn more about it visit my blog here on Hive and the first post where I introduced it.
Solution to the previous quiz: a1 1 Between lines 1 and 4 we are simply creating a dictionary using the comprehension notation.
Although this notation which spans seveal lines looks strange to some and is discouraged by others, it seems to be necessary when the line of code is very long, so it would fit well to span several lines. I personally like it and find it easily readable. Programmers in other languages are sometimes confused by this notation, but they soon get the hang of it.
As we can see, r: f"{f}{r}" is what defines the keys and values of the dictionary. The variable r is from the for loop we see below, while the f-string also makes use of r and another variable f which also changes value at each interaction. Here f and r stand for file and rank.
We see that the values of r and f start from zip("abcde", range(1,5)). We know that this zip function traverses two iterables at the same time. The first iterable is the string "abcde" of length 5, but the second iterable is range(1,5) which decomposed consists of 1,2,3,4, meaning its length is 4.
That tells us that the dictionary d will actually be formed like this: {1: 'a1', 2: 'b2', 3: 'c3', 4: 'd4'}. The pair 5: 'e5' does not exist, since we already know that the 5 in the range is exclusive. This already helps us to rule out some of the options given for the quiz, such as the option a1 e5. The content of this dictionary, by the way, is an analogy to the squares of a long diagonal of the chessboard.
Once the dictionary is created, line 5 applies the pop method to it. Did you think this method only existed for lists? No, dictionaries also support it. How does it work in this case? Well, the first value we provide to the method corresponds to a key in the dictionary, while the next value is a default value that pop will return in case the given key does not exist in the dictionary, similar to how the get method works.
Although the pop method receives the key searched, it actually returns the value corresponding to that key. Hence in our case, when doing: d1, d2 = d.pop(1, 0), d.pop(5, 1), d1 will have the value 'a1', since key 1 exists and has the value 'a1', while d2 will have the value 1, which is the default value given to pop, since key 5 does not exist in the dictionary d.
By the way, you should know that the pop method is destructive, that is, it overwrites the dictionary, in this case removing key/values.
Finally when printing d1 and d2 we get that the output is 'a1 1', as expected.
If you want to blog about computer science and programming content, I invite you to join Hive and participate in its communities, such as STEM-social, Develop Spanish, Programming & Dev and others.
Bienvenido a mi nueva serie de Quizzes de Programaci贸n, en la cual podr谩s poner a prueba tus conocimientos y habilidades sobre programaci贸n y desarrollo de software de una manera sencilla y divertida. Si quieres aprender m谩s sobre ella visita mi blog aqu铆 en Hive y el primer post donde la present茅.
Soluci贸n al quiz anterior: a1 1 Entre las l铆neas 1 y 4 simplemente estamos creando un diccionario usando la notaci贸n de comprensi贸n.
Aunque esta notaci贸n que abarca varias l铆neas parece extra帽a para algunos y otros la desaconsejan, parece ser necesaria cuando la l铆nea de c贸digo es muy larga, por lo que encajar铆a bien el abarcar varias l铆neas. A m铆 personalmente me gusta y lo encuentro f谩cil de leer. Los programadores de otros lenguajes a veces se sienten confundidos por esta notaci贸n, pero pronto le toman el hilo.
Como podemos ver, r: f"{f}{r}" es lo que define las claves y valores del diccionario. La variable r es del bucle for que vemos a continuaci贸n, mientras que la cadena f tambi茅n hace uso de r y otra variable f que tambi茅n cambia valor en cada interacci贸n. Aqu铆 f y r representan file (columna) y rank (fila).
Vemos que los valores de r y f comienzan desde zip("abcde", range(1,5)). Sabemos que esta funci贸n zip atraviesa dos iterables al mismo tiempo. El primer iterable es la cadena "abcde" de longitud 5, pero el segundo iterable es range(1,5) que descompuesto consta de 1,2,3,4, lo que significa que su longitud es 4.
Eso nos dice que el diccionario d en realidad se formar谩 as铆: {1: 'a1', 2: 'b2', 3: 'c3', 4: 'd4'}. El par 5: 'e5' no existe, ya que ya sabemos que el 5 en el range es exclusivo. Esto ya nos ayuda a descartar algunas de las opciones dadas para el quiz, como por ejemplo la opci贸n a1 e5. El contenido de este diccionario, por cierto, es una analog铆a con las casillas de una gran diagonal del tablero de ajedrez.
Una vez creado el diccionario, la l铆nea 5 le aplica el m茅todo pop. 驴Pensabas que este m茅todo s贸lo exist铆a para listas? No, los diccionarios tambi茅n lo admiten. 驴C贸mo funciona en este caso? Bueno, el primer valor que proporcionamos al m茅todo corresponde a una clave en el diccionario, mientras que el siguiente valor es un valor predeterminado que pop devolver谩 en caso de que la clave dada no exista en el diccionario, similar c贸mo funciona el m茅todo get.
Aunque el m茅todo pop recibe la clave buscada, en realidad devuelve el valor correspondiente a esa clave. Por lo tanto en nuestro caso, al hacer: d1, d2 = d.pop(1, 0), d.pop(5, 1), d1 tendr谩 el valor 'a1', ya que la clave 1 existe y tiene el valor 'a1', mientras que d2 tendr谩 el valor 1, que es el valor predeterminado dado a pop, ya que la clave 5 no existe en el diccionario d.
Por cierto, debes saber que el m茅todo pop es destructivo, es decir, sobrescribe el diccionario, en este caso eliminando claves/valores.
Finalmente, al imprimir d1 y d2 obtenemos que la salida es 'a1 1', como se esperaba.
Si quieres bloguear sobre contenido inform谩tico y de programaci贸n, te invito a unirte a Hive y participar en sus comunidades, tales como STEM-social, Develop Spanish, Programming & Dev y otras.