Random shuffle each 2 letters in a word - python

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

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'
>>>

Code
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
Walkthrough
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.

Related

Split String sequentially every possible split

I'm struggling with ideas for this python script:
I have a string of characters, say abcdefghijklmnopqrstuvwxyz
I need to split these into a list, with 7 characters each, resulting in a list that has
[abcdefg], [bcdefgh], [cdefghi], ... , [tuvwxyz]
as elements.
I have this method, but it currently outputs
['abcdefg', 'hijklmn', 'opqrstu', 'vwxyz']
...
def chunksOf7(toSplit):
chunks = [toSplit[i:i+7] for i in range(0, len(toSplit), 7)]
print(chunks)
Any ideas?
You can use a list comprehension to iterate over slices of the string of length 7.
>>> s = 'abcdefghijklmnopqrstuvwxyz'
>>> [s[i:i+7] for i in range(len(s)-6)]
['abcdefg', 'bcdefgh', 'cdefghi', 'defghij', 'efghijk', 'fghijkl', 'ghijklm', 'hijklmn', 'ijklmno', 'jklmnop', 'klmnopq', 'lmnopqr', 'mnopqrs', 'nopqrst', 'opqrstu', 'pqrstuv', 'qrstuvw', 'rstuvwx', 'stuvwxy', 'tuvwxyz']
If I understand correctly, you want the output lists to shift only one character each. So instead of iterating the range(len(toSplit)-6) in steps of 7, it should use steps of 1.
A simple way:
>>> import string
>>> to_split = string.ascii_lowercase
>>> [to_split[i:i+7] for i in range(0, len(to_split)-6)]
['abcdefg', 'bcdefgh', 'cdefghi', 'defghij', 'efghijk', 'fghijkl', 'ghijklm', 'hijklmn', 'ijklmno', 'jklmnop', 'klmnopq', 'lmnopqr', 'mnopqrs', 'nopqrst', 'opqrstu', 'pqrstuv', 'qrstuvw', 'rstuvwx', 'stuvwxy', 'tuvwxyz']
As a function:
def chunksOf7(to_split):
return [
to_split[i:i+7]
for i in range(0, len(to_split)-6)]

How to count occurrences of a list of string inside of a list in python?

For example my list is
lst=['hello','world','this','is','hello','world','world','hello']
subString=['hello','world']
The result I'm looking for is in this case is 2 since the list ['hello','world'] occurs twice with that same order.
I tried doing
list(filter(lambda x : x in substring,lst))
but that returns all of hello and world
You could use " ".join() on both lists to create a string and then use str.count() to count the number of occurrences of subString in lst
lst=['hello','world','this','is','hello','world','world','hello']
subString=['hello','world']
l = " ".join(lst)
s = " ".join(subString)
count = l.count(s)
print("Joined list:", l)
print("Joined substring:", s)
print("occurrences:", count)
outputs:
Joined list: hello world this is hello world world hello
Joined substring: hello world
occurrences: 2
Using the window generator from this answer and a Counter, this can be expressed as:
from collections import Counter
lst=['hello','world','this','is','hello','world','world','hello']
subString=('hello','world')
counts = Counter(window(lst, len(subString)))
print(counts[subString])
# 2
If you want to skip the Counter, you could do
print(sum(x == subString for x in window(lst, len(subString))))
You can join the elements into a list of lists and then filter by those that match your substring array.
joinedWords = [lst[n:n + len(subString)] for n in range(0, len(lst), len(subString))]
# => [['hello', 'world'], ['this', 'is'], ['hello', 'world'], ['world', 'hello']]
filtered = list(filter(lambda x: x == subString, joinedWords))
print(len(filtered)) # 2
Since all elements are string in this case, I'd create a string from each list, then count the occurrences of the second string in the first string:
lst=['hello','world','this','is','hello','world','world','hello']
subString = ['hello','world']
s = ' '.join(lst)
subs = ' '.join(subString)
print(s.count(subs))

How to read user command input and store parts in variables

So let's say that user types !give_money user#5435 33000
Now I want to take that user#5435 and 33000 and store them in variables.
How do I do that? Maybe it is very simple but I don't know.
If you need any more info please comment.
Thanks!
list_of_sub_string=YourString.split()
print(list_of_sub_string[-1]) #33000
print(list_of_sub_string[-2]) #user#5435
Split the input on spaces and extract the second and third elements:
parts = input().split()
user = parts[1]
numb = parts[2]
Although it would be more Pythonic to unpack into variables (discarding the first with a conventional underscore):
_, user, numb = input().split()
Just to elaborate further, input.split() returns a list of the sublists split at the deliminator passed into the function. However, when there are no inputs, the string is split on spaces.
To get a feel, observe:
>>> 'hello there bob'.split()
['hello', 'there', 'bob']
>>> 'split,on,commas'.split(',')
['split', 'on', 'commas']
and then unpacking just assigns variables to each element in a list:
>>> a, b, c = [1, 2, 3]
>>> a
1
>>> b
2
>>> c
3

How to print list items which contain new line?

These commands:
l = ["1\n2"]
print(l)
print
['1\n2']
I want to print
['1
2']
Is it possible when we generate the list outside of the print() command?
A first attempt:
l = ["1\n2"]
print(repr(l).replace('\\n', '\n'))
The solution above doesn't work in tricky cases, for example if the string is "1\\n2" it replaces, but it shouldn't. Here is how to fix it:
import re
l = ["1\n2"]
print(re.sub(r'\\n|(\\.)', lambda match: match.group(1) or '\n', repr(l)))
Only if you are printing the element itself (or each element) and not the whole list:
>>> a = ['1\n2']
>>> a
['1\n2']
>>> print a
['1\n2']
>>> print a[0]
1
2
When you try to just print the whole list, it prints the string representation of the list. Newlines belong to individual elements so get printed as newlines only when print that element. Otherwise, you will see them as \n.
You should probably use this, if you have more than one element
>>> test = ['1\n2', '3', '4\n5']
>>> print '[{0}]'.format(','.join(test))
[1
2,3,4
5]
Try this:
s = ["1\n2"]
print("['{}']".format(s[0]))
=> ['1
2']

Python - How to add space on each 3 characters?

I need to add a space on each 3 characters of a python string but don't have many clues on how to do it.
The string:
345674655
The output that I need:
345 674 655
Any clues on how to achieve this?
Best Regards,
You just need a way to iterate over your string in chunks of 3.
>>> a = '345674655'
>>> [a[i:i+3] for i in range(0, len(a), 3)]
['345', '674', '655']
Then ' '.join the result.
>>> ' '.join([a[i:i+3] for i in range(0, len(a), 3)])
'345 674 655'
Note that:
>>> [''.join(x) for x in zip(*[iter(a)]*3)]
['345', '674', '655']
also works for partitioning the string. This will work for arbitrary iterables (not just strings), but truncates the string where the length isn't divisible by 3. To recover the behavior of the original, you can use itertools.izip_longest (itertools.zip_longest in py3k):
>>> import itertools
>>> [''.join(x) for x in itertools.izip_longest(*[iter(a)]*3, fillvalue=' ')]
['345', '674', '655']
Of course, you pay a little in terms of easy reading for the improved generalization in these latter answers ...
Best Function based on #mgilson's answer
def litering_by_three(a):
return ' '.join([a[i:i + 3] for i in range(0, len(a), 3)])
# replace (↑) with you character like ","
output example:
>>> x="500000"
>>> print(litering_by_three(x))
'500 000'
>>>
or for , example:
>>> def litering_by_three(a):
>>> return ','.join([a[i:i + 3] for i in range(0, len(a), 3)])
>>> # replace (↑) with you character like ","
>>> print(litering_by_three(x))
'500,000'
>>>
a one-line solution will be
" ".join(splitAt(x,3))
however, Python is missing a splitAt() function, so define yourself one
def splitAt(w,n):
for i in range(0,len(w),n):
yield w[i:i+n]
How about reversing the string to jump by 3 starting from the units, then reversing again. The goal is to obtain "12 345".
n="12345"
" ".join([n[::-1][i:i+3] for i in range(0, len(n), 3)])[::-1]
Join with '-' the concatenated of the first, second and third characters of each 3 characters:
' '.join(a+b+c for a,b,c in zip(x[::3], x[1::3], x[2::3]))
Be sure string length is dividable by 3

Categories

Resources