Python Adjacent Indices Challenge

In this article we will look at how to use Python to determine whether two indices in a list are adjacent. Say you have a list like in the image, where the indices are marked, starting at 0 as is usual for Python and many other languages.

Python List Indices

How do we determine whether two indices are adjacent?

In other words, complete the following function stub to make all the assertions correct, where a and b are two list indices you wish to consider.

def is_next_to(a, b):

assert is_next_to(0, 0) is False
assert is_next_to(0, 1) is True
assert is_next_to(1, 0) is True
assert is_next_to(0, 3) is False
assert is_next_to(1, 2) is True
assert is_next_to(2, 1) is True
assert is_next_to(4, 1) is False

If you have an idea how to approach this, go ahead now and complete the function definition. If you need a hint, click below.

Solution to Python Adjacent Indices Challenge

Once you’ve had a go, check my solution below.

Yours may look a bit different, but as long as the logic is correct then well done!

Python Adjacent Indices Challenge Extension

The idea for this challenge came from a slightly more complex problem I needed to solve.

Imagine you have a circular array, where the last element is adjacent to the first, and you wish to determine whether two indices are in fact adjacent.

Circular List Python

The situation is similar to above, but now we need to account for where 0 is one one the indices. For generality, I’ve made the function accept an additional argument n to give the length of the array (Python list) whose indices we wish to consider.

This gives us the modified stub and assertions to compete:

def is_next_to_circular(n, a, b):

n = 6
assert is_next_to_circular(n, 1, 1) is False
assert is_next_to_circular(n, 1, 2) is True
assert is_next_to_circular(n, 0, 1) is True
assert is_next_to_circular(n, 5, 0) is True
assert is_next_to_circular(n, 4, 3) is True
assert is_next_to_circular(n, 3, 4) is True

Have a go now.

Solution Python Adjacent Indices Challenge Extension

And here’s a solution:

This article has been about a Python challenge to find whether two indices are adjacent, both in a normal list and a circular list. I hope you enjoyed it.

Happy Computing!

Sharing is caring!

Leave a Reply

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