My Coding Quiz #18

My Coding Quiz #18 👨‍💻🛠️🧩

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: Most likely output is five. To understand this solution, one must first understand the program, of course. Since it's a slightly long script, I'm reinserting it below for better context:




Previous quiz
By @eniolw

Let's understand what we have here. First we import the standard module random which will allow us to use some functions that require pseudo-random.

Then we define a function called getVal that at the end of the day will return an integer value from a list passed as an argument. Here's the function:

def getVal(l):
    a, b = random.sample(l, 2)
    try: return int(a, 2)
    except: 
        l.remove(a)
        a = random.sample(l, 1)[0]
        return int(a, 2)


In there we see that first two values are picked at random from the list l using the sample function. This function returns a new list which is then unpacked into the variables a and b.

Then starts a try ... except clause where we try to convert the value of a to an integer. We see that this is accomplished with the int function, but note that this takes 2 as its second argument. That argument tells the function that the value of a is a base 2 number expressed as a string.

If an error occurs, the except block is executed. What it does is remove the value that caused the error from the given list and take a new sample of the list and convert it to an integer, returning that value.

Then we see a top-level code corresponding to the main program:


str = "0b10,0b01,0g101,0b11,0b00"
data = str.split(",")
n1, n2 = getVal(data), getVal(data)
print(n1 + n2)


First a string is defined: str = "0b10,0b01,0g101,0b11,0b00" from which a list data is created using str.split("," ), resulting in ["0b10", "0b01", "0g101", "0b11", "0b00"].

If we're familiar with the Python representation of binaries, we'll recognize that these are the binary numbers "0b00", which is 0, "0b01", which is 1, "0b10", which is 2, and "0b11", which is 3. Notice that "0g101" is an invalid literal as the 'g' makes the notation wrong.

Next, we call the function getVal twice supplying it with this list, thus getting two integer values n1 and n2 that are added together and whose result is printed at the end.

The complexity of the exercise is that sample will select random values, so we don't get the same output every time. So how do we determine the answer? We can use the elimination method, testing each hypothesis for truth until we find something that makes it false. Let's see:

The program cannot crash?

Although there is an invalid value in the binary list, the getVal function is equipped with a try ... except that will allow it to handle this potential exception, so yes, the program cannot fail.

The maximum possible output is even?

The list of binaries has the numbers 0, 1, 2 and 3. The largest of these is 3, which is a value that both n1 and n2 can take. The sum 3 + 3 is 6, which is an even number. So, yes, the maximum possible result is even.

The length of data can change?

We are talking about the data list defined in the main program. The list is passed as an argument to getVal, which can modify it with the remove method if an exception occurs. You can modify it since lists are passed by reference. So yes, the length of data can change.

The most likely outcome is five?

We see that both n1 and n2 can take random values between 0 and 3 and that the final result is the sum of these two values. It is the same principle as rolling two dice, except that here it would be two 4-sided dice, where the faces can be 0, 1, 2 and 3. Here I will show a table with the possible combinations and we will see which one value is the mode:


dices

We see that 3 is the most common sum value, so it is the most likely. It has exactly a probability of 4/16 or 1/4 or what is the same 25%. Since three is the most likely outcome, that invalidates the statement that the most likely output is five, making it false, and thus we get the correct answer.

Well, @splash-of-angs63 participated this time, though not successfully. I hope this does not discourage us.


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, Hive Learners and others.


Mi Quiz de Programación #18 👨‍💻🛠️🧩

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: El resultado más probable es cinco. Para entender esta solución hay que primero entender el programa, claro está. Dado que es un script ligeramente largo, lo reinserto a continuación para mejorar el contexto:


Quiz
Por @eniolw

Entendamos lo que tenemos aquí. Primero importamos el módulo estándar random que nos permitirá usar algunas funciones que requieren del pseudoazar.

Luego definimos una función llamada getVal que al final del día devolverá un valor entero a partir de una lista pasada como argumento. He aquí la función:

def getVal(l):
    a, b = random.sample(l, 2)
    try: return int(a, 2)
    except: 
        l.remove(a)
        a = random.sample(l, 1)[0]
        return int(a, 2)


Vemos que primero se escogen dos valores al azar de la lista l usando la función sample. Esta función devuelve una nueva lista que pasa a ser desempaquetada en las variables a y b.

Luego comienza una cláusula try ... except donde intentamos convertir el valor de a en un entero. Vemos que ello se logra con la función int, pero notamos que esta toma 2 como segundo argumento. Ese argumento le indica a la función que el valor de a es un string de base 2.

Si ocurre un error, el bloque except es ejecutado. Lo que hace es eliminar el valor que produjo un error de la lista dada y vuelve a tomar una muestra de la lista y convertirla a entero, devolviendo ese valor.

Luego vemos un código del más alto nivel correspondiente al programa principal:


str = "0b10,0b01,0g101,0b11,0b00"
data = str.split(",")
n1, n2 = getVal(data), getVal(data)
print(n1 + n2)


Primero se define una cadena de caracteres: str = "0b10,0b01,0g101,0b11,0b00" con la cual se crea una lista data usando str.split(","), resultando en ["0b10", "0b01", "0g101", "0b11", "0b00"].

Si estamos familiarizados con la representación de binarios en Python, reconoceremos que estos son los números binarios "0b00", que es 0, "0b01", que es 1, "0b10", que es 2 y "0b11", que es 3. Por su parte, "0g101" es un literal inválido, la 'g' hace a la notación incorrecta.

Luego, llamamos a la función getVal dos veces suministrándole esta lista, para así obtener dos valores enteros n1 y n2 que se suman y cuyo resultado se imprime al final.

La complejidad del ejercicio radica en que sample seleccionará valores aleatorios, haciendo que no obtengamos una misma salida cada vez. Entonces, ¿cómo determinamos la respuesta? Podemos usar el método de eliminación, comprobando la veracidad de cada hipótesis hasta que encontremos algo que la haga falsa. Veamos:

¿El programa no puede fallar?

Aunque hay un valor incorrecto en la lista de binarios, la función getVal está equipada con un try ... except que le permitirá manejar esta potencial excepción, de modo que sí, el programa no puede fallar.

¿El resultado máximo posible es par?

La lista de binarios posee los números 0, 1, 2 y 3. El mayor de estos es 3, que es un valor que puede tener tanto n1 como n2. La suma 3 + 3 es 6, que es un número par. Por lo tanto, sí, el resultado máximo posible es par.

¿La longitud de data puede cambiar?

Hablamos de la lista data definida en el programa principal. La lista es pasada como argumento a getVal, la cual puede modificarla con el método remove de ocurrir una excepción. Puede modificarla puesto que las listas son pasadas por referencia. Por lo tanto, sí, la longitud de data puede cambiar.

¿El resultado más probable es cinco?

Vemos que tanto n1 como n2 pueden tomar valores al azar entre 0 y 3 y que el resultado final es la suma de estos dos valores. Es el mismo principio que tirar dos dados, excepto que aquí serían dos dados de 4 caras, donde las caras pueden ser 0, 1, 2 y 3. Aquí mostraré una tabla con la combinaciones posibles y veremos cuál valor es la moda:


dices

Vemos que 3 es el valor de suma más común, por lo que es el más probable. Exactamente tiene una probabilidad de 4/16 o 1/4 o lo que es lo mismo 25%. Dado que tres es la salida más probable, eso invalida la aseveracion de que el resultado más probable es cinco, haciéndola falsa y con ello obtenemos la respuesta correcta.

Bueno, @splash-of-angs63 participó esta vez, aunque no con éxito. Espero ello no nos desanime.


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, Hive Learners y otras.

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