Swapping consecutive element in a list with a probability in Python


I want to swap consecutive elements in list with a probability. For example, I have this list:


I wrote the following code thats swap the consecutive elements

length=len(l) if len(l)%2==0 else len(l)-1
for i in range(0,length,2):

The above code results in the following :


However, what I want to do is to use a probability for the swap. Let’s assume the probability of a swap is 50%. So only 50% of time the swap will happen. Any idea how to achieve this?

Asked By: mars



If you are writing code that needs some sort of probability, you are guaranteed to only find a possible solution using the random library.

A possible way to solve it is to choose from a choice of true and false and implement the swap when true. Since there are only two possible choices, (true and false), and you are choosing at random(pseudo-random actually), there is a 50% chance of picking each one.

That will look like this:

import random
length=len(l) if len(l)%2==0 else len(l)-1
for i in range(0,length,2):
    if random.choice([True, False]): #only swap is true is chosen

That should a be a useful workaround.
I can’t help but wonder why you need that particular behaviour though.

Answered By: NGY
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.