Two solutions but not two results [solved] | Sololearn: Learn to code for FREE!

0

Two solutions but not two results [solved]

I realise this is a very theoretical problem. But in my code https://code.sololearn.com/cO5N7UzCfAdu/#py lines 7/8 and 10/11 contain independent solutions to the given problem. When run individually on their own they work and return the reversed string. When I have them both in the same code, I expected to get the same output (reversed string) twice. But it only appears once. Does anybody know why that is ? Thanks!

7/9/2020 9:02:18 PM

Matthias

6 Answers

New Answer

+5

Matthias The iterator returned by reversed is exhausted by the join method resulting in a StopIteration state and it can't be reset to its original state. So it can't be used more than once. Solution: c = list(reversed(a.split()))

+4

Matthias Because c is an object. Just print c and see what you get. You need to change for i in d: Here is correct solution: ------------------ a = "This is a test" c = reversed(a.split()) d = ' '.join(c) print(d) for i in d: print(i, end = "")

+3

Thanks Kevin! That explains it. And also thanks to the other replies. Much appreciated!

0

Thanks but what I meant was the following. This code works on its own: a="This is a test" c=reversed(a.split()) for i in c: print(i, end=" ") And this code also works on its own: a="This is a test" c=reversed(a.split()) d=' '.join(c) print(d) When combined they should return the same result twice. But I get it only once.

-1

Matthias Give me a sample input and output