My Coding Quiz #37

in FreeCompliments8 months ago

My Coding Quiz #37 👨‍💻🛠️🧩

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.

Without further ado, here's the riddle...




Quiz
By @eniolw


What's your choice?

Solution to the previous quiz: {'vote': True, 'comment': False, 'done': False}. This script is a nod to the previous edition, as it suggests that it talks about curation.

We start by defining two dictionaries d1 and d2 that represent data. Then we define the function is_done where all the interesting stuff happens. Basically it returns a dictionary that is formed by combining two received dictionaries a and b and adding a new key 'done'.

To combine the dictionaries we use the unpack operator (**) as it is in the code, which does exactly the same thing as the Javascript spread operator (...). Interestingly, this usage has been around in Python for a long time before JavaScript incorporated its spread operator. We also see that, as to be expected in dictionary merging, keys are overwritten, as in the case of 'comment' in a which is True, but is overwritten by the value of 'comment' in b which is False.

We can still define keys within the dictionary declaration, as in the case of 'done'. Its value is obtained by applying the function all that evaluates if all the elements of the iterable are Truthy. We see that we give this function the list [*a.values(), *b.values()] that has been composed using the unpack operator in lists (*), which is also equivalent to the spread operator of Javascript applied to arrays.

We need to use the values method on a and b to get the iterables of the values in those dictionaries and these iterables are unpacked by the asterisk, so we get the list [True, True, True, False]. The function all will therefore return False because not all values in the list are truthy. In short, is_done returns the dictionary {'vote': True, 'comment': False, 'done': False} and is printed at the end.

As we can see, depending on what we want to merge or extend, in Python we must use * in case of lists and ** in case of dictionaries. Most programmers are familiar with them in the context of the optional function parameters *args and **kargs, where in fact, they just follow the same principle, but their use can actually be applied beyond that and can enrich your code.


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.


Mi Quiz de Programación #37 👨‍💻🛠️🧩

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é.

Sin más preámbulos, he aquí el acertijo...




Quiz
Por @eniolw


¿Cuál es tu elección?

Solución al quiz anterior: {'vote': True, 'comment': False, 'done': False}. Este script es un guiño a la edición anterior, ya que sugiere que habla de curación.

Comenzamos definiendo dos diccionarios d1 y d2 que representan datos. Luego definimos la función is_done donde suceden todas las cosas interesantes. Básicamente devuelve un diccionario que se forma combinando dos diccionarios recibidos a y b y agregando una nueva clave 'done'.

Para combinar los diccionarios utilizamos el operador de desempaquetado (**) tal como está en el código, que hace exactamente lo mismo que el operador spread de Javascript (...). Curiosamente, este uso ha existido en Python durante mucho tiempo antes de que JavaScript incorporara su operador spread. También vemos que, como es de esperar en la combinación de diccionarios, las claves se sobrescriben, como en el caso de 'comment' en a que es True, pero se sobrescribe con el valor de 'comment' en b que es False.

No conforme con ello, podemos definir claves dentro de la declaración del diccionario, como en el caso de 'done'. Su valor se obtiene aplicando la función all que evalúa si todos los elementos del iterable son verdaderos. Vemos que le damos a esta función la lista [*a.values(), *b.values()] que ha sido compuesta usando el operador desempaquetado en listas (*), que también es equivalente al operador de spread de Javascript aplicado a arreglos.

Necesitamos usar el método values en a y b para obtener los iterables de los valores en esos diccionarios y estos iterables se desempaquetan por el asterisco, por lo que obtenemos la lista [True, True, True, False]. Por lo tanto, la función all devolverá False porque no todos los valores de la lista son verdaderos. En resumen, is_done devuelve el diccionario {'vote': True, 'comment': False, 'done': False} y se imprime al final.

Como podemos ver, dependiendo de lo que queramos fusionar o extender, en Python debemos usar * en el caso de listas y ** en el caso de diccionarios. La mayoría de los programadores están familiarizados con ellos en el contexto de los parámetros de función opcionales *args y **kargs, donde, de hecho, siguen el mismo principio, pero su uso puede variar y en realidad se puede aplicar más allá de eso y puede enriquecer tu código.


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.

Sort:  

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord 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. 
 

!DHEDGE

you have 0.0 vote calls available today, your vote calls will reset at next snapshot. You can buy DHEDGE on Tribaldex or earn some daily by joining one of our many delegation pools at app.dhedge.cc to increase your daily amount.