Here’s a fun Python coding challenge that can be adapted to different levels of ability. Remember the game Duck Duck Goose from school? You sit in a circle and one player walks around tapping each player in turn saying “duck”, until they unexpectedly change to saying “goose” and a chase follows…

The challenge in Python is:

Given a list containing between 2 and 26 “players”, represented by strings `"A"`

, `"B"`

, `"C"`

etc., and a positive integer `goose`

, print out the player who will be the “goose”.

So for example, if we have

`ducks = ["A", "B", "C", "D"]`

and

`goose = 2`

we print `"B"`

(Remember Python list indices start at `0`

so we’ll need to account for that in our code… It seems more in keeping with the spirit of the playground to start counting at 1…)

That’s fairly straightforward, assuming you know how to access an element in a list at a particular position, but what if `n`

is bigger than the list length?

To access the list element at position

`i`

we use`my_list[i]`

(zero-based indexing).

This is where the Modulo Operator `%`

comes in. It is a very important tool in Python and other programming languages, and is well worth spending some time getting familiar with. In this case, if we envisage the list as “wrapping” back on itself from the end to the start, then the “clock arithmetic” interpretation of `%`

is very relevant.

So have a go now at one of the two following versions, depending on whether you have learned about functions yet.

## Python Duck Duck Goose Challenge Basic Version

```
# Duck Duck Goose Basic Version
ducks = ["A", "B", "C", "D"]
goose = 10
# Print the duck at position `goose`, assuming we start counting at 1.
# The result should be "B" here.
```

This may take a little unpacking…

We used `goose % 4`

to find the position give or take some whole circuits around the list, then we used an offset to account for the fact that Python uses zero-based indexing. If using `- 1`

instead of `+ 1`

seems strange, spend a few moments thinking about why this is in fact correct.

## Python Duck Duck Goose Challenge Function

Make your function able to handle varying length lists of ducks…

```
# Duck Duck Goose using a function
def duck_duck_goose_2(duck_list, goose_pos):
pass
ducks = ["A", "B", "C", "D"]
print(duck_duck_goose_2(ducks, 4)) # D
print(duck_duck_goose_2(ducks, 10)) # B
```

The solution here can be a one-liner, and uses the same logic as the basic version above. However, it accounts for varying list lengths by using `len(duck_list)`

. Have a go with some different length lists to make sure your solution still works.

This post has been about a fun Python coding challenge based on the school-yard game Duck Duck Goose. I hope you found it interesting and that you learned something along the way.

Happy computing!