Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a string in python based on block size in python

Im trying to reverse a string based on the block size given

for example

"the price of food is 12 dollars" and im given a block size of 4

i want the end result to be:

food of price the dollars 12 is

im not sure how to input this into python any help would be appreciated i need this to work for any block size

like image 288
user2272942 Avatar asked Apr 12 '13 05:04

user2272942


People also ask

How do you reverse a slice in Python?

To reverse a list in Python, you can use negative slicing: As you want to slice the whole list, you can omit the start and stop values altogether. To reverse the slicing, specify a negative step value. As you want to include each value in the reversed list, the step size should be -1.

How do you reverse a string in Python without function?

Method 4: Reverse string in Python using an extended slice Extended slice offers to put a “step” field as [start, stop, step], and giving no field as start and stop indicates default to 0 and string length respectively, and “-1” denotes starting from the end and stop at the start, hence reversing a string.


2 Answers

def chunks(seq, n):
    return [seq[i:i+n] for i in range(0, len(seq), n)]

s = "the price of food is 12 dollars"
' '.join(' '.join(reversed(chunk)) for chunk in chunks(s.split(), 4))

Related: How do you split a list into evenly sized chunks in Python?

like image 87
wim Avatar answered Nov 13 '22 20:11

wim


Using itertools grouper recipe:

>>> from itertools import izip_longest
>>> def grouper(n, iterable, fillvalue=None):
        "Collect data into fixed-length chunks or blocks"
        # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
        args = [iter(iterable)] * n
        return izip_longest(fillvalue=fillvalue, *args)

>>> text = "the price of food is 12 dollars"
>>> ' '.join(word for g in grouper(4, text.split()) 
                  for word in reversed(g) if word)
'food of price the dollars 12 is'
like image 28
jamylak Avatar answered Nov 13 '22 18:11

jamylak