Перемещение по списку строк - PullRequest
1 голос
/ 19 апреля 2020

У меня есть следующее упражнение, где у меня есть список directions = ["N", "E", "S", "W"] для каждого из направлений на компасе. Я должен сделать функцию, где, если вы введете «N», он возвращает следующий по часовой стрелке «E». Когда вы введете «W», он должен go вернуться к началу и вернуть «N». Когда ввод отсутствует в списке, например, «F», он не должен возвращать ничего. Вот что я придумал:

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)

Это работает только тогда, когда я даю ввод "N". Когда я удаляю else, он работает и для других элементов, но затем не возвращается к началу, когда ввод «W». Интересно, как я могу сделать так, чтобы код соответствовал заданию или есть ли более простой способ сделать это.

Ответы [ 2 ]

6 голосов
/ 19 апреля 2020
def turn_clockwise(direction):
    directions = ["N", "E", "S", "W"]
    if direction in directions:
        return directions[(directions.index(direction) + 1) % len(directions)]
    else:
        return None

Чтобы обернуть вещи вокруг указанного c числа, используется оператор по модулю%.


Здесь с предложением @AKX:

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
0 голосов
/ 19 апреля 2020

Вы также можете использовать готовый cycle из itertools.cycle :

from itertools import cycle

directions = cycle(["N", "E", "S", "W"])

for _ in range(10):
    print(next(directions), end = " -> ")
print(next(directions))

Вывод:

N -> E -> S -> W -> N -> E -> S -> W -> N -> E -> S

или просто создать запрос поиска.

Обе версии в используемом методе:

from itertools import cycle

def next_dir(what):
    d = "NESW"
    directions = cycle(d)
    if what in d:   
        while next(directions) != what:
            pass
        return next(directions)
    else:
        raise ValueError(what + " not possible")


def next_lookup(what):
    d = {"N":"E", "E":"S", "S":"W", "W":"N"}
    r = d.get(what)
    if r: 
        return r
    raise ValueError(what+" not possible")

for l in "NESW":
    print(l, next_dir(l)) 
    print(l, next_lookup(l)) 

try:
    print(next_dir("q"))
except Exception as e:
    print(e)

try:
    print(next_lookup("q"))
except Exception as e:
    print(e)

Вывод:

N E  # next_dir
N E  # next_lookup  .. etc ..
E S
E S
S W
S W
W N
W N
q not possible
q not possible
...