Hi,
I need to write a program that will reverse the first k characters for every 2k characters.
If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the others as original.
So for example:
if k=2 and string = 'lemons' then the final output should be elmosn
if k=2 and string = 'abcdefg' then final output should bacdfeg
I gave it a shot by assuming k=2 and therefore 2k=4 so I need to reverse the first two characters for every 4 characters in my string(='lemons'). This is how far I got but am stuck:
I have replaced
I need to write a program that will reverse the first k characters for every 2k characters.
If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the others as original.
So for example:
if k=2 and string = 'lemons' then the final output should be elmosn
if k=2 and string = 'abcdefg' then final output should bacdfeg
I gave it a shot by assuming k=2 and therefore 2k=4 so I need to reverse the first two characters for every 4 characters in my string(='lemons'). This is how far I got but am stuck:
def f(string): string = [string[x:x+4] for x in range(0,len(string),4)] print(string) t=[] for word in string: newString =[word[x:x+2][::-1] for x in range(0,1)] #how do I retain the 3rd and 4th character in 'lemo' so that it gives 'elmo' -- the 'mo' is missing t.append(newString) return t c = f('lemons') print(c)this is my output so far:
['lemo', 'ns'] [['el'], ['sn']]
I have replaced
newString =[word[x:x+2][::-1] for x in range(0,1)]with
newString =[word[x:x+2][::-1]+x[2:] for x in range(0,1)], so that helps to give me the rest of the characters
def f(string): string = [string[x:x+4] for x in range(0,len(string),4)] print(string) t=[] for word in string: if len(word) == 4: newString =[word[x:x+2][::-1]+word[2:] for x in range(0,1)] elif (len(word)<4) and (len(word)>=2): newString =[word[x:x+2][::-1]+word[2:] for x in range(0,2,2) elif len(word)<2: newString = word[::-1] t.append(newString) return ''.join(newString)why is the above giving me the following error:
line 8 elif(len(word)<4) and (len(word)>=2): ^ SyntaxError: invalid syntax