python sets river crossing puzzle

Have you heard of the puzzle about the farmer, the wolf, the goat and the cabbage?

You can play it here (click the “run” button to start):

There are many different ways to implement the logic, but here I chose to use Python Sets. My goal here is to teach about Python programming. If you just want to enjoy the puzzle, with some nice graphics, there’s some great versions on here on Trunsum Maths.

Python Sets

A set in Python is defined as “an unordered collection of unique elements”

Sets are a less known but very useful data structure in Python. There are two properties which make them especially helpful for solving certain types of problems.

  • Sets are unordered
  • Sets can not contain duplicate elements.

The second property can lead to a lot of confusion. So let’s be clear about an important point: set declaration is different to the data structure. The declaration can have duplicates but not the structure itself.

So, a set declared by my_set = {1, 2, 2, 5} will be stored and displayed as {1, 2, 5} (potentially with the elements in any order).

This distinction between declaration and representation can lead to exactly opposite answers to the question “can sets contain duplicate elements?” and it really depends on what the person asking actually means. The correct answer is no, assuming they are asking about the actual data structure.

Basic Set Operations in Python

Have a go at creating and modifying some sets. Print your sets as you go to check they are displaying what you expect. Also, don’t limit yourself to integer elements – try string and other data types too.

Python Sets Challenge

Once you’ve had a bit of practice with sets, try and solve the following challenge: complete the definition for contains_duplicates() which takes a list as an argument and returns a boolean describing whether the list contains duplicate elements or not.

Python Sets Challenge Solution

Python Version of the Farmer, the Wolf, the Goat and the Cabbage Puzzle

Here’s a listing of the code for the Farmer, the Wolf, the Goat and the Cabbage Puzzle in Python. It is designed to be run in a console, so has a clear method to clear the console to keep things tidy. You may prefer to use the Trinket version, but don’t forget to add brackets to the print statements as Trinket uses Python 2.7.

Happy Computing. Robin Andrews.

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Join our mailing list

Join our mailing list to receive awesome articles about learning Python and Computer Science in a fun and accessible way, straight to your inbox.

 Take your Python skills to the next level!

with our free email course on object oriented programming with Python