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.

2
  • 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. Commented Jun 8, 2015 at 9:29
  • Why are you using input() and raw_input()? Do you know they are different? Commented Jun 8, 2015 at 9:34

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

See stackoverflow.com/questions/9475241/… 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.
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)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.