Friday, November 9, 2018

Q7:Reverse every other word in the string

Question 7: Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are apart of the word.

Sample 1:
Input: "I really hope it works this time..."
Output: "I yllaer hope ti works siht time..."

Sample 2:
Input: "Reverse this string, please!"
Output : "Reverse siht string, !esaelp"

5 comments:

  1. inp_str = input("Enter the string: ")
    spl_out = inp_str.split()
    output = ' '.join((list(map(lambda x: x if spl_out.index(x) % 2 == 0 else x[::-1], spl_out))))
    print(output)

    ReplyDelete
  2. def reverse_alternate(string):
    a=string.strip().split()
    return ' '.join([a[i] if i%2==0 else a[i][::-1] for i in range(0,len(a))])
    print(reverse_alternate(input()))

    ReplyDelete
  3. string = "I really hope it works this time..."
    string = "Reverse this string, please!"
    output = [st[::-1] if (i+1) % 2 == 0 else st for i, st in enumerate(string.split())]
    print(" ".join(output))

    ReplyDelete