Search code examples
pythonpython-3.xcycle

Cycling through a list of strings


I have the following exercise where I have a list directions = ["N", "E", "S", "W"] for each of the directions on a compass. I have to make a function where if you input "N" it returns the next one in clockwise direction "E". When you have input "W" it should go back to the start and return "N". When the input is not on the list e.g. "F" it should return none. This is what I have come up with:

def turn_clockwise(direction):
    directions = ["N", "E", "S", "W"]
    for i in range(3):
        if direction == directions[i]:
            result = directions[i+1]
            print(result)
        else:
            return(None)

This works only when I give input "N". When I remove the else it works for the other items as well however then it doesn't cycle back to the start when the input is "W". I wonder how I can make the code fit the assignment or if there is an easier way to do this.


Solution

  • def turn_clockwise(direction):
        directions = ["N", "E", "S", "W"]
        if direction in directions:
            return directions[(directions.index(direction) + 1) % len(directions)]
        else:
            return None
    

    To wrap things around a specific number the modulo % operator is used.


    Here with @AKX suggestion:

    def cycle(values, current): 
        try:
            return values[(values.index(current) + 1) % len(values)]
        except ValueError:
             print(f"{current} not in {values}")
    
    def turn_clockwise(direction):
        directions = ["N", "E", "S", "W"]
        if direction in directions:
            return cycle(directions, direction]
        else:
            return None