Shorten the list of tuples by cutting out loops?

I have a function that generates a list of tuples like:

[(0, 0), (1, 1), (1, 2), (1,3), (2, 4), (3, 5), (4, 5)]

which are used to represent the path of the tiles (row, column) in the game I am making.

The function I use to create these paths is not ideal, as it often creates loops, as shown below:

[(2, 0), (2, 1), (1, 2), (0, 3), (0, 4), (1, 5), (2, 5), (3, 4), (3, 3),
 (3, 2), (4, 1)]

Image

Instead, the path should look like this:

[(2, 0), (2, 1), (3, 2), (4, 1)]

Image

These paths can contain any number of cycles, which can be of any size and shape.

So my question is: how to write a function in python that shortens the list of loops and returns a new, shorter list that does not have these loops.

My attempt below:

def Cut_Out_Loops(Path):

    NewList = list(Path)
    Cutting = True

    a = 0
    for Cords in Path:
        a += 1

        try:
            for i in range(a + 2, len(Path)):
                if (Path[i][0] == Cords[0] and abs(Path[i][1] - Cords[1]) == 1:
                    NewList = NewList[0:a] + NewList[i:]
                    Path = list(NewList)
                elif Path[i][1] == Cords[1] and abs(Path[i][0] - Cords[0]) == 1:
                    NewList = NewList[0:a] + NewList[i:]
                    Path = list(NewList)
                elif abs(Path[i][0] - Cords[0]) == 1 and abs(Path[i][1] - Cords[1]) == 1:
                    NewList = NewList[0:a] + NewList[i:]
                    Path = list(NewList)
                elif abs(Path[i][1] - Cords[1]) == 1 and abs(Path[i][0] - Cords[0]) == 1:
                    NewList = NewList[0:a] + NewList[i:]
                    Path = list(NewList)
                Cutting = False
        except IndexError:
            Cutting = True
+4
source share
2 answers

"" ,

def clean(path):
    path1 = []
    for (x1,y1) in path:
        for (i,(x2,y2)) in enumerate(path1[:-1]):
            if abs(x1-x2) <= 1 and abs(y1-y2) <= 1:
                path1 = path1[:i+1]
                break
        path1.append((x1,y1))
    return path1

:

 >>> path = [(2, 0), (2, 1), (1, 2), (0, 3), (0, 4), (1, 5), (2, 5), (3, 4), (3, 3), (3, 2), (4, 1)]
 >>> clean(path)
 [(2, 0), (2, 1), (3, 2), (4, 1)]

, . .

+2

? 1000 , :

path = [
    (2, 0),
    (2, 1),
    (1, 2),
    (0, 3),
    (0, 4),
    (1, 5),
    (2, 5),
    (3, 4),
    (3, 3),
    (3, 2),
    (4, 1)
]


def adjacent(elem, next_elem):
    return (abs(elem[0] - next_elem[0]) <= 1 and
            abs(elem[1] - next_elem[1]) <= 1)

new_path = []
i = 0
while True:
    elem = path[i]
    new_path.append(elem)
    if i + 1 == len(path):
        break
    j = len(path) - 1
    while True:
        future_elem = path[j]
        if adjacent(elem, future_elem):
            break
        j -= 1
    i = j

print new_path
+1

Source: https://habr.com/ru/post/1650734/


All Articles