Question

I'm currently working on a text based adventure game. It's my final assignment for a programming course and I got the tip from one of the instructors to use modulus to decrease the amount of code to accomplish this:

def viable(self, north_south, east_west): 
    i = north_south.index(self)
    j = east_west.index(self)
    if i == 0:
        south = north_south[len(north_south)-1]
    else:
        south = north_south[i-1]
    if i == len(north_south)-1:
        north = north_south[0]
    else:
        north = north_south[i+1]
    if j == 0:
        west = east_west[len(east_west)-1]
    else:
        west = east_west[i-1]
    if j == len(east_west)-1:
        east = east_west[0]
    else:
        east = east_west[j+1]

    viable = [east, west, north, south]
    return viable

If any one could give any suggestions on how to bind the last index and the first index together?

Was it helpful?

Solution

Using % modules makes your code a lot simpler, yes, as it removes the need to test for the edge cases:

def viable(self, north_south, east_west): 
    i = north_south.index(self)
    j = east_west.index(self)

    south = north_south[(i - 1) % len(north_south)]
    north = north_south[(i + 1) % len(north_south)]
    west = east_west[(j - 1) % len(east_west)]
    east = east_west[(j + 1) % len(east_west)]

    return east, west, north, south

In other words, just add or subtract from your index, then apply the length as a modulus to 'wrap around' to the other side.

Let's say your list length is 5, then % 5 gives you the following outputs for various cases:

>>> 5 % 5  # last index + 1
0
>>> -1 % 5  # first index - 1
4
>>> 3 % 5  # middle + 1
3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top