[Python] Generate a random derangement of a list

Discussão em 'Python' iniciado por Stack, Setembro 25, 2024.

  1. Stack

    Stack Membro Participativo

    How can I randomly shuffle a list so that none of the elements remains in its original position?

    In other words, given a list A with distinct elements, I'd like to generate a permutation B of it so that

    • this permutation is random
    • and for each n, a[n] != b[n]

    e.g.

    a = [1,2,3,4]
    b = [4,1,2,3] # good
    b = [4,2,1,3] # good

    a = [1,2,3,4]
    x = [2,4,3,1] # bad


    I don't know the proper term for such a permutation (is it "total"?) thus having a hard time googling. The correct term appears to be "derangement".

    Continue reading...

Compartilhe esta Página