Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List problem
#1
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:

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
Reply
#2
Quote:
        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]
if and all its corresponding elifs need to be on the same indentation level.
Recommended Tutorials:
Reply
#3
done thank you
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with "Number List" problem on HackerRank Pnerd 5 2,034 Apr-12-2022, 12:25 AM
Last Post: Pnerd

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020