Shuffle a python list without using the built-in function

前端 未结 3 1768
情书的邮戳
情书的邮戳 2021-01-15 18:31

I\'m working on writing two different shuffle functions.

The first shuffle function must take a list and return a new list with the elements shuffled into a random o

3条回答
  •  滥情空心
    2021-01-15 18:46

    You might find that this implementation for shuffling suits your needs. Make sure that you note the difference between the two functions before using them.

    import copy
    import random
    
    
    def main():
        my_list = list(range(10))
        print(my_list)
        print(shuffle(my_list))
        print(my_list)
        shuffle_in_place(my_list)
        print(my_list)
    
    
    def shuffle(container):
        new_container = copy.copy(container)
        shuffle_in_place(new_container)
        return new_container
    
    
    def shuffle_in_place(container):
        for index in range(len(container) - 1, 0, -1):
            other = random.randint(0, index)
            if other == index:
                continue
            container[index], container[other] = container[other], container[index]
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题