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


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.

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center