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!

9th Jul 2020, 9:02 PM
Matthias Seidl
4 Answers
+ 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()))
9th Jul 2020, 9:27 PM
Kevin ★
+ 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 = "")
9th Jul 2020, 9:09 PM
A͢J
A͢J - avatar
+ 3
Thanks Kevin! That explains it. And also thanks to the other replies. Much appreciated!
9th Jul 2020, 9:38 PM
Matthias Seidl
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.
9th Jul 2020, 9:28 PM
Matthias Seidl