Scramble Strings in a given Python List
In this tutorial, we will look at how to scramble strings in a given Python list. We will look at a simple implementation of this task in Python. We will make use of the sample() inbuilt function found in the random module.
Scramble Strings in a list
In this section, we try to understand the problem. In case anyone requires it, here is a quick refresher on lists in Python.
I believe we can understand the problem better with the help of an example. So let’s consider the list ‘l’ defined below.
l = ['cat', 'dog', 'Monkey', 'POTATO', 'guiTAr']
Our concern is to ‘scramble the strings in the list’. We do NOT want to shuffle the order of strings. That is, we do NOT want the output to be of the form
Monkey guiTAr dog cat POTATO
We want the output to be of the form
tac ogd nMekyo OTTOAP TgAriu
Understanding the sample() function
The sample() function is present in the random module. You can read the full documentation here.
- sample(population, k) takes 2 arguments and returns a list. ‘population’ refers to a population sequence or set. For our problem, this refers to a string. ‘k’ is the length of the list returned and cannot be greater than the length of the string.
- The list returned by sample() is generated by taking elements of the string without replacement.
Suppose, our string, ‘s’, is given as follows. We create and print a list of 4 elements as follows.
s = 'ballOOns' print(sample(s, 4))
Our output will be similar to
['n', 'l', 'O', 'l']
['b', 's', 'a', 'l']
Note that if there are multiple occurrences of an element in the string, the list may have elements that repeat. However, they will not appear more than the number of times they are present in the string. For the above example, we will NOT get the following outputs.
['O', 'a', 'O', 'O']
['b', 'b', 'O', 'l']
Having understood these concepts, we ask ourselves the following question.
‘What happens if ‘k’ is assigned the length of the string?’
We see that the list returned needs to have ‘k’ elements of the string without replacement. That is, we get a list containing all the characters of the string (in a random manner).
Gives an output similar to
['a', 'n', 'O, 's, 'b, 'l', 'O', 'l']
Now that we have the list, we can convert it into a string using any of the methods given here.
Implementation in Python: Scramble Strings in a given List
The following code works in Google Colab. Appropriate changes can be made according to the platform on which the program is run.
from random import sample # l is a list of the strings and can be modified acoordingly l = ['cat', 'dog', 'Monkey', 'POTATO', 'guiTAr'] for i in l: print(''.join(sample(i, len(i)))
act gdo eyMonk POTOAT rATiug
Please note that the output changes each time as it is random.
In this tutorial, we looked at how to scramble strings in a given Python. We specifically dealt with the use of the sample() function present in the random module.