5

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

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
user2272942
  • 63
  • 1
  • 1
  • 8

3 Answers3

6
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?

Community
  • 1
  • 1
wim
  • 338,267
  • 99
  • 616
  • 750
5

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'
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 1
    @root you can't, because then it uses another extra space. @wim's solution avoids this problem by have two `''.join`s, which I like better now. Try it for yourself to see – jamylak Apr 12 '13 at 05:50
1

You are essentially splitting the list, reversing it, then rotating it.

So this works:

>>> st='the price of food is 12 dollars'
>>> li=st.split()[::-1]
>>> n=3
>>> print ' '.join(l[n:]+l[:n])
food of price the dollars 12 is

Or, more directly:

>>> li='the price of food is 12 dollars'.split()[::-1]
>>> print ' '.join(li[3:]+li[:3])
food of price the dollars 12 is

Or, if you want it in a function:

def chunk(st,n):
    li=st.split()[::-1]  # split and reverse st
    return ' '.join(li[n:]+li[:n])

print chunk('the price of food is 12 dollars',3)    

The key is:

st='the price of food is 12 dollars'  # the string
li=st.split()                         # split that
li=li[::-1]                           # reverse it
li=li[3:]+li[:3]                      # rotate it
' '.join(li)                          # produce the string from 'li'
dawg
  • 98,345
  • 23
  • 131
  • 206
  • +1 this is nice too awesome, what you doing first split into list reverse list then add back in chunks of block in string..Correct ?? – Grijesh Chauhan Apr 12 '13 at 06:13
  • Yes -- I added an explanation in the answer. – dawg Apr 12 '13 at 06:36
  • -1 this does not work for other cases. for example, for input of 'a b c d e f' and chunk size of 2 we should get 'b a d c f e' but yours gives 'd c b a f e' – wim Nov 07 '13 at 15:14