My Coding Quiz #39

in Programming & Dev5 months ago

My Coding Quiz #39 👨‍💻🛠️🧩

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: ['Tue', 'Thu']. We start by defining a function getWeekDay that expects to receive a number. We see that it returns one of the options contained in the dictionary, which is the name of the day of the week depending on the key number. To prevent errors due to non-existent key, we have used the get method with a default value to return.

This way of programming using a dictionary to choose options is very popular in Python due to the absence of a switch case clause in it, although Python 3.10 finally already incorporates something similar called match case.

Then in the main program we create a list schedule using list comprehension. Some programmers disagree with this way of denoting or using list comprehensions, but there is no definitive agreement or convention on this. Let's take a closer look:

schedule = [
    n for d in range(1,7) 
    if d % 2 == 0 and 
       (n := getWeekDay(d)) and 
       not n.startswith('S')
]

The expression n for d in range(1,7) indicates that the list will consist of the values of n in an iteration from 1 to 6 (7 is excluded). We see that d % 2 == 0 indicates that only the even values are selected which could be 2,4 and 6.

With these values, we obtain their alphabetical code with the instruction (n := getWeekDay(d)). Here we have used the walrus operator which is an innovation of Python 3.8. Therefore, if you run this code in an earlier Python, it will give you a syntax error. This operator is very handy and powerful. What it does is to create and assign variables in the middle of expressions. In our case, we created the variable n and assigned it what getWeekDay returns. The variable n comes into existence from then on and we see that it is renewed at each iteration.

The last condition not n.startswith('S') indicates that the alphabetic code for the day of the week must not start with S. Days 2, 4 and 6 correspond to 'Tue', 'Thu' and 'Sat', but 'Sat' is discarded because of what we said. Therefore, the schedule list contains only 'Tue' and 'Thu'.


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

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: ['Tue', 'Thu']. Comenzamos definiendo una función getWeekDay que espera recibir un número. Vemos que nos devuelve una de las opciones contenidas en el diccionario, la cual es el nombre del día de la semana dependiendo del número de clave. Para evitar errores debido a una clave inexistente, hemos utilizado el método get con un valor predeterminado para devolver.

Esta forma de programar usando un diccionario para elegir opciones es muy popular en Python debido a la ausencia de una cláusula switch case en él, aunque Python 3.10 finalmente ya incorpora algo similar llamado match case.

Luego, en el programa principal creamos una lista schedule usando la comprensión de listas. Algunos programadores no están de acuerdo con esta forma de denotar o utilizar listas por comprensión, pero no existe un acuerdo o convención definitivo al respecto. Echemos un vistazo más de cerca:

schedule = [
    n for d in range(1,7) 
    if d % 2 == 0 and 
       (n := getWeekDay(d)) and 
       not n.startswith('S')
]

La expresión n for d in range(1,7) indica que la lista estará formada por los valores de n en una iteración del 1 al 6 (7 es excluido). Vemos que d % 2 == 0 indica que solo se seleccionan los valores pares que podrían ser 2,4 y 6.

Con estos valores obtenemos su código alfabético con la instrucción (n := getWeekDay(d)). Aquí hemos utilizado el Operador Walrus que es una innovación de Python 3.8. Por lo tanto, si ejecutas este código en una versión anterior de Python, obtendrás un error de sintaxis. Este operador es muy práctico y potente. Lo que hace es crear y asignar variables en medio de expresiones. En nuestro caso, creamos la variable n y le asignamos lo que devuelve getWeekDay. La variable n entra en existencia a partir de ese momento y vemos que se renueva en cada iteración.

La última condición not n.startswith('S') indica que el código alfabético para el día de la semana no debe comenzar con S. Los días 2, 4 y 6 corresponden a 'Tue', 'Thu' y 'Sat', pero se descarta 'Sat' por lo que dijimos. Por lo tanto, la lista schedule contiene sólo 'Tue' y 'Thu'.


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.