Enio avatar

My Coding Quiz #48

eniolw

Published: 27 Feb 2024 › Updated: 27 Feb 2024My Coding Quiz #48

My Coding Quiz #48

My Coding Quiz #48 👨‍💻🛠️🧩

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@eniolw


What's your choice?

Solution to the previous quiz: 30. Let's describe the code step by step. After importing the random module, we define the list a with numeric elements. The expression 15*2 inside the brackets is resolved or replaced by 30.

Then to obtain list b we use the sample method of random, which obtains a sublist of randomly selected elements from another given list, or in other words, a shuffle. This is the built-in pythonian solution as opposed to kind of hack Javascript offers, as we discussed in a previous installment.

Within this line, however, things get a bit more obscure. The expression x:= a * 2 applies the walrus operator to create and use the variable x inline. That variable is a duplicate of the list a, that is, [30, 10, 65, 30, 65, 10, 30, 30, 30, 10, 65, 30, 65, 65, 10, 30]. As x comes into existence, we can access the size of that list, which is the second argument that sample takes, that is, the size of the sample.

Line 4 also looks tricky: c = max(set(b), key=x.count). It is actually a form of a reducer function. What it actually does is to select the element of b that is most frequent. To do this, we first convert it to a set for optimisation purposes and then provide the function x.count to key, which tells the max function to get the frequency of each element of set(b) in the list x. As 30 is repeated 6 times in x, it becomes the most frequent value, which is the one selected by max.

With this code you can then get the most repeated value in a list. Remember that it is important to convert the list to be iterated into a set to avoid iterating more than necessary. With it we iterate over 3 items ([30, 10, 65]), but without it, we would have iterated over 14 items, several of which are repeated, getting the frequency of each unnecessarily.


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

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@eniolw


¿Cuál es tu elección?

Solución al quiz anterior: 30. Describamos el código paso a paso. Después de importar el módulo random, definimos una lista a con elementos numéricos. La expresión 15*2 dentro de los corchetes se resuelve o reemplaza por 30.

Luego, para obtener la lista b utilizamos el método sample de random, que obtiene una sublista de elementos seleccionados aleatoriamente de otra lista dada, o en otras palabras, una mezcla. Esta es la solución Pythoniana incorporada en lugar del tipo de hack que ofrece Javascript, como comentamos en una entrega anterior.

Sin embargo, dentro de esta línea las cosas se vuelven un poco más oscuras. La expresión x:= a * 2 aplica el operador walrus para crear y usar la variable x inline. Esa variable es un duplicado de la lista a, es decir, [30, 10, 65, 30, 65, 10, 30, 30, 30, 10, 65, 30, 65, 65, 10, 30]. Como x pasa a existir, podemos acceder al tamaño de esa lista, que es el segundo argumento que toma sample, es decir, el tamaño de la muestra.

La línea 4 también parece complicada: c = max(set(b), key=x.count). En realidad, es una forma de función reductora (reducer). Lo que realmente hace es seleccionar el elemento de b que es más frecuente. Para hacer esto, primero lo convertimos a un set para fines de optimización y luego proporcionamos la función x.count a key, que le indica al max que obtenga la frecuencia de cada elemento de set(b) en la lista x. Como 30 se repite 6 veces en x, se convierte en el valor más frecuente, que es el seleccionado por max.

Con este código puedes obtener el valor más repetido en una lista. Recuerda que es importante convertir la lista a iterar en un conjunto (set) para evitar iterar más de lo necesario. Con él iteramos sobre 3 elementos ([30, 10, 65]), pero sin él, habríamos iterado sobre 14 elementos, varios de los cuales se repiten, obteniendo la frecuencia de cada uno innecesariamente.


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.

Leave My Coding Quiz #48 to:

Written by

def me(): i = "Univ. Professor, software developer, open source lover, FIDE chess player, eternal learner, STEMSocial curator, Chess Brothers Project cofounder"

Read more #hive-197685 posts


Best Posts From Enio

We have not curated any of eniolw's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Enio