Skip to content
Advertisement

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:

JavaScript

I wrote the following code thats swap the consecutive elements

JavaScript

The above code results in the following :

JavaScript

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?

Advertisement

Answer

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:

JavaScript

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement