dimanche 9 mai 2021

random sampling without replacement in python

I have a code in python which does random sampling of elements in a list with replacement:

def generateSequence(self, length, allow_start=False,
                         allow_stop=False): length = int(length)
        sequence = ""
        while len(sequence) < length:
            sequence = sequence + secrets.choice(self.sseq)
            if allow_start == "false" or not allow_start:
                sequence = self._cleanStart(sequence)
            if allow_stop == "false" or not allow_stop:
                sequence = self._cleanStop(sequence)
        return sequence[:length]

The random sampling is done with the secrets module However, I want the sampling to be done without replacement. As such, I have modified the code and used the random.sample function:

def generateSequence(self, length, allow_start=False,
                         allow_stop=False): length = int(length)
        sequence = ""
        while len(sequence) < length:
            sequence = sequence + ", ".join(random.sample(self.sseq,1))
            if allow_start == "false" or not allow_start:
                sequence = self._cleanStart(sequence)
            if allow_stop == "false" or not allow_stop:
                sequence = self._cleanStop(sequence)
        return sequence[:length]

However, when I run the code I still get the selection with replacement. Any advice?




Aucun commentaire:

Enregistrer un commentaire