The left and right iterators add elements to the list

topic

There are two vectors, v1: [1,2,3,4], v2: [5,6,7,8]. Add elements to the list by displacing the left and right iterators, and get the result: [1,5,2,6,3,7,4,8].

the code

def ZigzagIterator(v1,v2):
    ls = []
    while (len(v1) > 0):
        ls.append(v1.pop(0))
        if v2:
            ls.append(v2.pop(0))
    if v2:
        return ls + v2
    return ls

print(ZigzagIterator([1,2,3,4],[5,6,7,8]))

result

[1, 5, 2, 6, 3, 7, 4, 8]

Guess you like

Origin blog.csdn.net/a_13572035650/article/details/128378202