Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any ways to scramble strings in python?

I'm writing a program and I need to scramble the letters of strings from a list in python. For instance I have a list of strings 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!

like image 289
Geparada Avatar asked May 30 '11 22:05

Geparada


People also ask

How do you jumble strings in Python?

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.

What is scrambled string?

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”.


1 Answers

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']
like image 150
Tim McNamara Avatar answered Oct 06 '22 08:10

Tim McNamara