My Coding Quiz #55

in #hive-1976858 months ago

My Coding Quiz #55 👨‍💻🛠️🧩

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: [{'checkmate': True}, {'checkmate': True}]. Line 1 creates a list a with an empty dictionary. However, by coding * 2, we have duplicated the contents of the list with two dictionaries, but in a way that will be relevant later.

In line 2 we do the same thing. We see that the commutative property applies without problems, but here the list with elements to replicate is empty, so that actually b consists of an empty list.

Line 3 is more complex: a[len(b) - 1].update({'checkmate': True}). We see that what we do is to update the dictionary contained in the position len(b) - 1, which is -1, since we already saw that b is an empty list. Therefore, when accessing a[-1], what we do is to access the last position of the list a, which contains a dictionary.

Therefore, we update its content with the hardcoded dictionary {'checkmate': True}. However, when executing the last line of the script, we see that both dictionaries in list a have the same content and that is because when we did the duplication in line 1, we made copies by reference; something that is expected with mutable and complex objects such as dictionaries. In other words, both elements of the list, which are dictionaries, are the same. They both have references to the same dictionary.

This could be overlooked by an unsuspecting programmer using that notation in line 1. In short, you should know that it does not create a new dictionary, but creates as many references to the same dictionary as the number of list items you want.


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 #55 👨‍💻🛠️🧩

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: [{'checkmate': True}, {'checkmate': True}]. La línea 1 crea una lista a con un diccionario vacío. Sin embargo, al codificar * 2, hemos duplicado el contenido de la lista con dos diccionarios, pero de una manera que será relevante más adelante.

En la línea 2 hacemos lo mismo. Vemos que la propiedad conmutativa se aplica sin problemas, pero aquí la lista con elementos a replicar está vacía, por lo que en realidad b consta de una lista vacía.

La línea 3 es más compleja: a[len(b) - 1].update({'checkmate': True}). Vemos que lo que hacemos es actualizar el diccionario contenido en la posición len(b) - 1, que es -1, ya que ya vimos que b es una lista vacía. Por tanto, al acceder a a[-1], lo que hacemos es acceder a la última posición de la lista a, que contiene un diccionario.

Por lo tanto, actualizamos su contenido con el diccionario codificado {'checkmate': True}. Sin embargo, al ejecutar la última línea del script, vemos que ambos diccionarios en la lista a tienen el mismo contenido y eso se debe a que cuando hicimos la duplicación en la línea 1, hicimos copias por referencia; algo que se espera con objetos mutables y complejos como los diccionarios. Es decir, ambos elementos de la lista, que son diccionarios, son iguales. Ambos tienen referencias al mismo diccionario.

Esto podría ser pasado por alto por un programador desprevenido que use esa notación en la línea 1. En resumen, debes saber que no se crea un nuevo diccionario, sino que crea tantas referencias al mismo diccionario como el número de elementos de la lista que desees.


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:  

Awesome. This serie is a very good idea. You can also try with something like "find the error in this code". That will be very interesting too.

I'll even check on previous episodes 😅👍

That's a good suggestion. Thank you!

Thank you!

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. 
 

Cool quiz. @tipu curate 8

Sorry, please curate posts not older than 1 day.

Thank you! BTW, the tipu command didn't work apparently 😅

Yeah, I noticed. Maybe the bot is having issues.

@tipu curate 8

Sorry, please curate posts not older than 1 day.

Congratulations @eniolw! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You got more than 3500 replies.
Your next target is to reach 3750 replies.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

Hive Power Up Day - April 1st 2024
Happy Birthday to the Hive Blockchain