Shuffle a python list without using the built-in function

前端 未结 3 1805
情书的邮戳
情书的邮戳 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:52

    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
    

提交回复
热议问题