Lesson / Lección 7: Even Harder Challenges

Reeborg Progress
100%

If you’ve gotten to this point, you’re definitely ready to move on to the next lessons. But if you want to push yourself….

Exercise: Maze

The code for this solution is actually not too complicated implement, but it’s very challenging to devise a strategy to solve. In this problem, we will get a lot of practice with psuedocoding and coming up with solutions to complex problems.

Guiding Questions:

  • If you were stuck in a maze, what strategy would you use to try to escape?
  • Let’s try tracing our way through Reeborg’s maze. What happens if you always try to go left when you can? What happens if you always try to go right when you can?

Think about the right-hand rule typically implemented in maze solvers. If you don’t know the right-hand rule, it basically states that if you follow the maze while always having your hand on the right wall, eventually you’ll reach the edge. One tip we have is to write down some psuedo-code. Psuedo-code us a simplified version of the code you want to write but in a way you can still think about it without using coding syntax.

The maze solution has the following pseudo-code:

 1.  Have Reeborg follow along the right edge of the maze
 2. Turn right if Reeborg can
 3. Go straight ahead if Reeborg can't turn right
 4. Turn left as a last resort

With the pseudo-code written up, it’s much easier to see that the natural structure of this solution requires if/elif/else statements.

If/Elif/Else Statements

We discussed If/Else statements before. There is another condition that you can but in this conditional statement. Elif(read as Else If) is put between If and Else and has a conditional statement that is different from If and Else. If an If/Elif/Else statement, it checks if the If condition is true, if it is not correct, then the computer checks the Elif and check that statement. If that condition is true, it’ll run the code, but if it is false, it’ll move onto the Else condition and run that. One last thing about these statements, you can have just If/Elif statements without Else statements since you may only want to check those conditions and if neither one is met, then we don’t run anything else.

For example, imagine that Reeborg is at an intersection in the world where both the right is clear (Reeborg can turn right) and the front is clear (Reeborg can go straight), and the first if statement in the code checks for if the front is clear and the second elif statement checks for if the right is clear. What does this code tell Reeborg to do? Is that the correct behavior according to the pseudo-code? What’s wrong with this code?”.

Which of these gives you the correct behavior?

if front_is_clear():
    #go straight
elif right_is_clear():
    #go right
...
if right_is_clear():
    #go straight
elif front_is_clear():
    #go right
...

Exercise: Checkerboard: the challenge

To find this exercise, first click, “Other Worlds”, then click “Go to Challenges”. After that you will find “Checkerboard: the challenge”.

To get back to the other challenges, you will have to click “Other Worlds again, then click “Go to Introduction Reeborg”.

This problem is very difficult! Despite potentially being somewhat straightforward to come up with a psuedocoded solution to it, the actually implementation to solving this is very messy. Careful decomposition will be very helpful here.

Guiding Questions:

  • What are some repeated tasks you will be doing in this problem that could be broken down into functions? If your strategy is to snake back and forth like this:
  • How would Reeborg act differently when advancing to the next row when it was coming from the left vs from the right?
  • How would we be able to tell the difference between the two situations?
  • How can Reeborg know when it’s done so that it doesn’t get in an infinite loop.

When writing functions for this problem three important things to focus on are:

  1. What situation will Reeborg be in when I use this function?
  2. What “work” will this function do?
  3. In what situation will Reeborg be after this function finishes.

Optionally, you can move on to “Checkerboard: the great challenge” after this problem you want to push yourself. I didn’t write up guiding questions to that one since we want you to be challenged.

That’s it! Feel free to poke around and try other exercises if you really want a challenge!


Si ha llegado a este punto, definitivamente está listo para pasar a las próximas lecciones. Pero si quieres esforzarte …

Ejercicio: Maze

El código para esta solución en realidad no es una implementación demasiado complicada, pero es muy difícil diseñar una estrategia para resolver. En este problema, practicaremos mucha psuedo-coding y buscaremos soluciones a problemas complejos.

Preguntas orientadoras:

  • Si estuvieras atrapado en un laberinto, ¿qué estrategia usarías para tratar de escapar?
  • Intentemos rastrear nuestro camino a través del laberinto de Reeborg. ¿Qué sucede si siempre intentas ir a la izquierda cuando puedes? ¿Qué sucede si siempre intentas ir bien cuando puedes?

Piense en la regla de la mano derecha implementada típicamente en solucionadores de laberintos. Si no conoce la regla de la mano derecha, básicamente establece que si sigue el laberinto mientras siempre tiene la mano en la pared derecha, eventualmente llegará al borde. Un consejo que tenemos es escribir un código psuedo. Psuedo-code nos ofrece una versión simplificada del código que desea escribir, pero de alguna manera aún puede pensar en ello sin usar la sintaxis de codificación.

La solución de laberinto tiene el siguiente pseudocódigo:

1. Haz que Reeborg te siga por el borde derecho del laberinto.
2. Gire a la derecha si Reeborg puede
3. Siga recto si Reeborg no puede girar a la derecha
4. Gire a la izquierda como último recurso.

Con el pseudocódigo escrito, es mucho más fácil ver que la estructura natural de esta solución requiere declaraciones if / elif / else.

Declaraciones If / Elif / Else

Discutimos las declaraciones If / Else antes. Hay otra condición que puede hacer, pero en esta declaración condicional. Elif (leído como Else If) se coloca entre If y Else y tiene una declaración condicional que es diferente de If y Else. Si una declaración If / Elif / Else, verifica si la condición If es verdadera, si no es correcta, entonces la computadora verifica el Elif y verifica esa declaración. Si esa condición es verdadera, ejecutará el código, pero si es falsa, pasará a la condición Else y lo ejecutará. Una última cosa acerca de estas declaraciones, puede tener solo declaraciones If / Elif sin declaraciones Else, ya que es posible que solo desee verificar esas condiciones y si no se cumple ninguna de las dos, entonces no ejecutamos nada más.

Por ejemplo, imagine que Reeborg está en una intersección en el mundo donde tanto la derecha está despejada (Reeborg puede girar a la derecha) como el frente está despejado (Reeborg puede ir recto), y la primera declaración if en el código verifica si el frente está claro y la segunda declaración elif verifica si el derecho está claro. ¿Qué le dice este código a Reeborg que haga? ¿Es ese el comportamiento correcto según el pseudocódigo? ¿Qué tiene de malo este código? “.

¿Cuál de estos te da el comportamiento correcto?

if front_is_clear():
    #sigue derecho
elif right_is_clear():
    #gira a la derecha
...
if right_is_clear():
    #sigue derecho
elif front_is_clear():
    #gira a la derecha
...

Ejercicio: Checkerboard: el desafío

Para encontrar este ejercicio, primero haga clic en “Other Words”, luego haga clic en “Go to Challenges”. Después de eso encontrarás “Checkerboard: el desafío”.

Para volver a los otros desafíos, deberá hacer clic en “Other words” nuevamente, luego hacer clic en “Intro to Reeborg”.

¡Este problema es muy difícil! A pesar de ser potencialmente sencillo encontrar una solución con código psuedo, la implementación real para resolver esto es muy complicada. La descomposición cuidadosa será muy útil aquí.

Preguntas orientadoras:

  • ¿Cuáles son algunas tareas repetidas que hará en este problema que podrían dividirse en funciones? Si su estrategia es serpentear de un lado a otro de esta manera:
  • ¿Cómo actuaría Reeborg de manera diferente al avanzar a la siguiente fila cuando venía de izquierda a derecha?
  • ¿Cómo podríamos distinguir la diferencia entre las dos situaciones?
  • ¿Cómo puede saber Reeborg cuándo está hecho para que no entre en un ciclo infinito?

Al escribir funciones para este problema, hay tres cosas importantes en las que centrarse son:

  1. ¿En qué situación estará Reeborg cuando use esta función?
  2. ¿Qué “trabajo” hará esta función?
  3. En qué situación estará Reeborg después de que termine esta función.

Opcionalmente, puede pasar a “Checkerboard : el gran desafío” después de este problema que desea forzar. No escribí preguntas orientadoras para eso porque queremos que seas desafiado.

¡Eso es! ¡Siéntete libre de hurgar y probar otros ejercicios si realmente quieres un desafío!