[Python] How can I correctly implement "starwars-order" of a sorted list?

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    We define starwars-order as an operation on a list of numbers, such that if the list is ordered, the first third moves to the center, the center third moves to the front and the last third stays put.

    The problem is as follows, given a list of numbers, give their starwars-order. For example for the Star wars movies, the starwars-order of 1,2,3,4,5,6,7,8,9 would be 4,5,6,1,2,3,7,8,9.

    enter image description here

    if __name__ == "__main__":
    n = int(input()) # Size of the list
    numbers = list(map(int, input().split())) # List of integers

    part_size = n // 3
    first_third = numbers[:part_size]
    second_third = numbers[part_size:2 * part_size]
    last_third = numbers[2 * part_size:]

    if numbers == sorted(numbers):
    result = second_third + first_third + last_third
    else:
    result = [
    first_third[0],
    last_third[0],
    *second_third,
    last_third[1] if len(last_third) > 1 else None,
    first_third[1] if len(first_third) > 1 else None
    ]

    # Remove None values from the result and print
    result = [x for x in result if x is not None]
    print(" ".join(map(str, result)))


    I tried this logic, if my input list is ordered, then apply the rule the question indicates, otherwise, given the observation of output 3, apply that sorting method, but it turned out I can only pass three test cases, most of test cases cannot be passed.

    Continue reading...

Compartilhe esta Página