I'm writing a program and I need to scramble the letters of string
s from a list
in python. For instance I have a list
of string
s like:
l = ['foo', 'biology', 'sequence']
And I want something like this:
l = ['ofo', 'lbyoogil', 'qceeenus']
What is the best way to do it?
Thanks for your help!
To shuffle strings or tuples, use random. sample() , which creates a new object. random. sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.
To scramble the string, we may choose any non-leaf node and swap its two children. For example, if we choose the node “gr” and swap its two children, it produces a scrambled string “rgeat”. rgeat / \ rg eat / \ / \ r g e at / \ a t. We say that “rgeat” is a scrambled string of “great”.
Python has batteries included..
>>> from random import shuffle
>>> def shuffle_word(word):
... word = list(word)
... shuffle(word)
... return ''.join(word)
A list comprehension is an easy way to create a new list:
>>> L = ['foo', 'biology', 'sequence']
>>> [shuffle_word(word) for word in L]
['ofo', 'lbyooil', 'qceaenes']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With