1

I don't understand why my code doesn't work.

The code is:

def trans(old):
    length = len(old)
    new = []
    new = old
    for i in range(0,length):
        print(old[length-i-1])
    for i in range(0,length):
        new[i] = old[length-i-1]
        print("new:",new[i],"  [i]:",i,"  old:",old[length-i-1]," length-
        i-1:",length-i-1)
    ihavenoideawhatimdoing = " ".join(new)
    return new

Instruction:
1. def trans(old): Input sentence in (old)
2. length(len): Take number of elements in the sentence
3. new = [] and new = old is to make a container with the same size for the new word
4. First for loop = I wanted to see the words in the original sentence backwards
5. My problem is in the second for loop. See the output
6. What comes next is related to the problem I'm solving but not to the problem I'm having

Output

Input sentence: "please help me solve this"

I didn't any label for the next batch of words but it's supposed to be:
old(length-0-1) -> old(5-0-1) -> old(4): this
old(3): solve
old(2): me
old(1):help
old(0): please

Now, what's iffy is in the next for statement at length-i-1 = 1 where instead of being "help", it's "solve."

Both codes are familiar so I'm stuck at what else could be wrong.

Monxstar
  • 9
  • 3
  • `new = old` makes the name `new` refer to the same object as `old`. So if you change the contents of one, the other is also changed. – RemcoGerlich May 03 '17 at 13:24
  • It doesn't just assign the contents for `old` into `new`? So *any* change into `new` is applied to `old`? edit: just saw the duplicate question. Thanks for helping~ – Monxstar May 03 '17 at 13:32
  • @Monxstar: `=` never copies anything, it just makes the name on the left refer to the value on the right. As they both refer to the same thing, a change is visible using both (but it's still only one object being changed). `new = list(old)` as AChampion says does make a new list with the contents of `old`. – RemcoGerlich May 03 '17 at 13:34
  • @AChampion: I have doubts that it is a string, as then he would have got an exception at the `new[i] = `line. – RemcoGerlich May 03 '17 at 13:34
  • @RemcoGerlich good point, assumed sentence = `str`. – AChampion May 03 '17 at 13:37

1 Answers1

0

Use this:

def trans(old):

    new = old.split(" ")
    new_str = ""
    for i in reversed(new):
        new_str = new_str + " " + i
    print new_str
Prakhar Verma
  • 457
  • 3
  • 12