1
votes

I'm writing a function that will create a new shuffled list (I can't use the built-in shuffle function)

def Shuf(aList):

  import random
  newList=[]
  for i in range(len(aList)):
      element=random.sample(aList,1)
      newList+=element
  return newList

This is what I have right now and it's working but when I return the shuffled list there are repeated elements of my list. How can I make my function only return the elements in the list one time?

4
Sampling runs the risk of selecting the same item multiple times -- as you've discovered. Rather than sampling, you might consider swapping as a strategy. - FMc
shuffle without shuffle, that sounds so much like homework... - Guillaume
@Guillaume +1 suspicious homework. However there are some things we can give you some guidance. First of all, do not import modules within a function, if you could avoid. Second, try explore the key built-in data structures that Python offers, and you might be surprised on 1. how easy this problem can be solved 2. how many ways this problem can be solved. - woozyking
Google "Fisher-Yates" - Lee Daniel Crocker

4 Answers

0
votes

Something like the next (not tested).

from random import choice

def get_list( l ):
    len_ = len( l )
    output = []

    for i in range( len_ ):
        index = choice( len( l ) )
        output.append( l[ index ] )
        del l[ index ]

    return output
0
votes

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]
>>> 
0
votes
  def shuffle_list(l):
     shuffled_list = []

     for i in range(len(l)):
       item = random.choice(l)
       shuffled_list.append(item)
       index = l.index(item)
       del l[ index ]
   return shuffled_list
shuffle_list([1,2,3,4,5,6])
# OUTPUT - [2, 1, 6, 5, 3, 4]
0
votes

Since you apparently can use random.sample:

import random

def Shuf(aList):
    return random.sample(aList, len(aList))