-8
class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        d=[]

        words=s.split()
        for i in words:
            d.append(i[::-1])
            print d
            result=" ".join(d)
        return result

Error:

UnboundLocalError: local variable 'result' referenced before assignment

Edit:-

result=" ".join(d)
print result

When I used this code in the last two lines I can see my stdout but null value is being returned and when I used these two lines in place of above:

result=" ".join(d)
return result

I get only the first word of the line.

Ex. "I am writing a code"

Expected output:- "edoc a gnitirw ma I "
Actual output: "edoc"

4
  • 1
    What exactly is your question? What research have you done? What value of s was used that got the error message? (In particular, was it the empty string?) Commented Jan 30, 2018 at 20:46
  • 2
    Works on my machine. Commented Jan 30, 2018 at 20:47
  • Your code does not raise any exceptions in my python. Commented Jan 30, 2018 at 20:48
  • Duplicate of stackoverflow.com/questions/29533098/… Commented Jan 30, 2018 at 22:29

1 Answer 1

1

The problem here is that you declared result only inside your loop. If you send an empty string, s.split() will return an empty list and result will never be declared.

Declare result also before the for loop with a default value and this exception should go away.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried that too but I got an error saying 'output limit exceeded'. I tried this on leetcode.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.