-1

I know there is already reverse solutions but can not figure concept out for the following question.

.wons sa etihw saw eceelf sti bmal elttil a dah yraM end

so it returns

Mary had a little lamb its fleece was white as snow.

Am I far off?

 line=raw_input()
 lines = []
 i = 0
 while line != "end":
     lines.append(line)
     line=raw_input()
 for line in lines[::-1]:
 print line

2 Answers2

0

There are a few things to tweak here.

It looks like you want to keep reversing user input until the input is 'end'

A simpler way to do that would be:

while True:                         # to set the loop going
    line = raw_input()
    if line == 'end': break         # to exit the loop

Following this, if the input is not 'end', you default to your reversal code:

    print line[::-1]      # notice the indentation

which is slick indexing.

If you want to save the reversed string, that's a different matter, but it's not clear that you want to do that.

This doesn't deal with a string having 'end' at the end . . . is that an essential part of this? Because it doesn't seem necessary to me.

If 'end' is always there (with or without the while loop):

line = raw_input()
print line[-5::-1]

which will reverse the whole thing, but will carve 'end' off the end first.

If this doesn't help, can you give some more information about what you want to achieve?

Stidgeon
  • 2,673
  • 8
  • 20
  • 28
-2

I am assuming that all your input has been accumulated in a single string and that the end marker has been stripped off. The overall strategy is:

  • split your line of raw text into an array of words
  • step through each of your words reversing the word string
  • reverse the order of the entries in your array of words
  • join the array entries together with intervening spaces.

In code (first broken out by the steps):

line = ".wons sa etihw saw eceelf sti bmal elttil a dah yraM"
words = line.split(" ")
words_letters_reversed = [ w[::-1] for w in words]
word_order_reversed = list(reversed(words_letters_reversed))
reassembled_into_a_string = " ".join(word_order_reversed)
print(reassembled_into_a_string)

=> "Mary had a little lamb its fleece was white as snow."

And then all at once:

result = " ".join(list(reversed(([ w[::-1] for w in line.split(" ")]))))
print(result)

=> "Mary had a little lamb its fleece was white as snow."