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.
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:
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:
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 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.
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.
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:
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.
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茅.
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:
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:
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.
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.
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.
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:
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.