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 PMMatthias
6 AnswersNew Answer
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()))
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 = "")
Thanks Kevin! That explains it. And also thanks to the other replies. Much appreciated!
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.
Matthias Give me a sample input and output