Home > Software engineering >  Swapping consecutive element in a list with a probability in Python
Swapping consecutive element in a list with a probability in Python

Time:09-21

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

l=[1,2,3,4,5,6,7,8,9,10,11]

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):
    l[i],l[i 1]=l[i 1],l[I]

The above code results in the following :

l=[2,1,4,3,6,5,8,7,10,9,11]

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?

CodePudding user response:

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
l=[1,2,3,4,5,6,7,8,9,10,11]
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
        l[i],l[i 1]=l[i 1],l[i]

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

  • Related