Codementor Events

Refining our code

Published Jan 28, 2024

Here’s a problem I recently worked on with a beginner.

The goal was to write the game Bulls and Cows. The first step was to write a function which would generate the 4-digit secret code (read the link if you don’t know how the game works).

So we started with something like this:

1.png

The code is represented as a list containing 4 unique digits. If we generate a digit that’s already in the code, we try again.

It works, but the while loop is a bit clunky. We know we’ll eventually generate a unique digit since there are at most 3 others digits in the list, but it feels like we could do better. The key is to not simply generate a random digit, but rather, choose from the digits we haven’t yet used.

2.png

That works and avoids the while loop because we’re always choosing a digit that isn’t currently in the code. Cleaner, but I challenged the student to go further. One of the best ways to learn to code better is to keep trying to refine your solution. Celebrate your working code, then see if you can solve it another way. Sometimes the new solution is better, other times it isn’t. But you won’t know until you try.

What if we took the digits from 0 to 9, as we did above, but simply shuffled them? Wouldn’t that produce a secret code without any extra work?
de) # shuffle it!

3.png

Discover and read more posts from Dave Wade-Stein
get started