Reputation: 188
Its possible to shuffle a word each two characters in a randomic way?
Like hello world
changed to ehllo owlrd
or hello wolrd
or ehll owolrd
.
I cant get something like the following results: olleh dlrow
and lleho wodlr
Upvotes: 0
Views: 457
Reputation: 40938
Break up the pairs of twos, sample, and recombine:
from random import sample
s = 'hello world'
twos = [s[i:i+2] for i in range(0, len(s), 2)] # Step 1
twos = ''.join([''.join(sample(two, len(two))) for two in twos]) # Step 2
print(twos)
ehll oowrld
Step 1 uses list comprehension, basically a condensed for-loop. Specifying
range(0, len(s), 2)
iterates over an object with a step size of 2. The best
way to easily visualize is to set i
equal to its progressive values:
s[0:0+2]
will give you 'he'
, and so on. The result of Step 1 is
['he', 'll', 'o ', 'wo', 'rl', 'd']
.
The inner part of Step 2 also uses list comprehension to iterate over each of
the pairs established in Step 1. for two in twos
says to perform the action
for each element in the list twos
established in the previous step. You could replace each instance of two
with any word that you like, such as pair
(just don't use a keyword). Then using ''.join()
concatenates the broken-up strings back together.
Note: this treats spaces as characters to involve in the shuffling.
Upvotes: 3
Reputation: 96324
Yes, put your string in some mutable data structure, like a list
. Then a straightforward algorithm would be to iterate by two, starting at the second item, and randomly swap:
>>> def shuffle_by_two(word):
... wordl = list(word)
... for i in range(1, len(word), 2):
... if random.randint(0, 1):
... wordl[i-1], wordl[i] = wordl[i], wordl[i-1]
... return ''.join(wordl)
...
So, for example:
>>> shuffle_by_two("hello world")
'hello wolrd'
>>> shuffle_by_two("hello world")
'hello wolrd'
>>> shuffle_by_two("hello world")
'ehllo owrld'
>>> shuffle_by_two("hello world")
'ehllo world'
>>> shuffle_by_two("hello world")
'hello owlrd'
>>> shuffle_by_two("hello world")
'ehll oowrld'
>>>
Upvotes: 4