Shuffle a python list without using the built-in function

南笙酒味 提交于 2019-12-01 12:47:33

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 random
>>> def shuffle(array):
    copy = list(array)
    shuffle_in_place(copy)
    return copy

>>> def shuffle_in_place(array):
    array_len = len(array)
    assert array_len > 2, 'Array is too short to shuffle!'
    for index in range(array_len):
        swap = random.randrange(array_len - 1)
        swap += swap >= index
        array[index], array[swap] = array[swap], array[index]


>>> array = list(range(10))
>>> array
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> shuffle(array)
[7, 2, 3, 5, 8, 6, 0, 1, 9, 4]
>>> array
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> shuffle_in_place(array)
>>> array
[8, 3, 1, 6, 9, 7, 0, 4, 2, 5]
>>> 

Plan: Go through the list from the beginning starting with element 0; find a new random position for it, say 6, put 0’s value in 6 and 6’s value in 0. Move on to element 1 and repeat this process, and so on through the rest of the list

import random
iteration = random.randint(2, 100)
temp_var = 0
while iteration > 0:
    # We will be swapping the value of i for j.
    # And then setting j to what i was using the temp_var place holder.
    for i in range(1, len(my_list)): # have to use range with len()
        for j in range(1, len(my_list) - i):
            # Using temp_var as my place holder so I don't lose values
            temp_var = my_list[i]
            my_list[i] = my_list[j]
            my_list[j] = temp_var

        iteration -= 1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!