My Coding Quiz #48

in #hive-19768510 months ago

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


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


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

Sort:  

I'm definitely going to have to visit the first post to get the overview. It's a pretty interesting journey. I'm amazed at how you've been consistent with a series to 48.

I guess I have to adopt your style of numbering my blog-isodes to keep track.

Thank you once again sir for sharing this great content.❤️

You don't need to number them if they're not a series. My posts of this series are chained.

Oh okay Sir, that's well noted.

Thank you so much ♥️

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. 
 

This post has been manually curated by @bhattg from Indiaunited community. Join us on our Discord Server.

Do you know that you can earn a passive income by delegating to @indiaunited. We share more than 100 % of the curation rewards with the delegators in the form of IUC tokens. HP delegators and IUC token holders also get upto 20% additional vote weight.

Here are some handy links for delegations: 100HP, 250HP, 500HP, 1000HP.

image.png

100% of the rewards from this comment goes to the curator for their manual curation efforts. Please encourage the curator @bhattg by upvoting this comment and support the community by voting the posts made by @indiaunited.

Thank you!