0

I've been trying to rearrange the string by reversing a particular strings consecutively from the given string input and the limit is given as input.

for example limit is 3

if input is Hellothegamestarts

output must be Heltolhegemastastr and it is saved in separate array The code is:

while True: 
    t = int(input())
    if t == 0:
        break

    string = raw_input()
    string = string.encode('utf-8')
    leng = len(string)
    r = t/leng
    m = []
    leng = 0

    for i in range(r):
        if r % 2 == 0:
            l = 0
            l = leng + t
            for i in range(t):
                temp = string[l]
                m.append(temp)
                l = l - 1
            r = r + 1


            leng = leng + t

        else:
            l = 0
            l = leng

            for i in range(t):
                temp = string[l]
                m.append(temp)
                l = l + 1

            r = r + 1


            leng = leng + t


    print m

the output i got is [] and asks for next input for t.

Any help is appreciated.

The6thSense
  • 8,103
  • 8
  • 31
  • 65
susil95
  • 300
  • 3
  • 5
  • 16
  • 7
    I'm afraid you should restructure your question; at least I don't understand what you're putting into and want to get out of your algorithm. – Marcus Müller Jun 08 '15 at 09:29
  • Why are you using `input()` and `raw_input()`? Do you know they are different? – cdarke Jun 08 '15 at 09:34

3 Answers3

2

Take the blocks in chunks of 3s, and reverse the odd ones, eg:

import re

s = 'Hellothegamestarts'
r = ''.join(
    el if idx % 2 == 0 else el[::-1] 
    for idx, el in enumerate(re.findall('.{,3}', s))
)
# Heltolhegemastastr
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • See http://stackoverflow.com/questions/9475241/split-python-string-every-nth-character for a few alternative approaches to split a string into chunks of 3. That being said, in case one already uses `itertools`, it might be nicer to zip the chunks with `[False, True, False, True, ...]` and then only reverse those elements which are `True`. – Frerich Raabe Jun 08 '15 at 10:10
1

Maybe you can try -

t = int(input())
if t == 0:
    break;

string = raw_input()
m = ''
leng = len(string)
i = 0
while i < leng:
    if (i/t) % 2 != 0:
        m = m + string[i+t-1:i-1:-1]
    else:
        m = m + string[i:i+t]
    i = i + t
print(m)
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

Alternatively you can try this

def  myfunc(s, count):
     return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]

a='Hellothegamestarts'
lst=myfunc(a,3)
print "".join([i if lst.index(i) in range(0,len(lst),2) else i[::-1] for i in lst])

myfun i didn't write it.It's from here

Ajay
  • 5,267
  • 2
  • 23
  • 30