Python string index out of range error


  • 0
    G

    I get " Line 8: IndexError: string index out of range" when submitting,but this code works just fine on my pc.
    Last input is 1,5.

    def fractionToDecimal(numerator, denominator):
        if(numerator%denominator==0):
            return str(numerator//denominator)
        ans = str(numerator/denominator)
        subs = ans[2:]
        if len(subs) == subs.count(subs[0]) and len(subs)>3:
            return ans[:2] + "(" + subs[0] + ")"
        return ans
    

    You can find my submission here: https://oj.leetcode.com/submissions/detail/17196047/
    Can you help me understand why I get the error?
    As I said this code works just fine when I run it on my pc using Python 3.4.2


  • 1
    P

    1.It is because the differences between Python 2 and 3 in integer division.
    In python 3: 1/2 results in 0.5 while it yields 0 in python 2.
    So here is the situation your code run into under python 2 (subs[0] is the problem in your if len(subs) == subs.count(subs[0]) and len(subs)>3):

    ans = str(1/5)  # '0' instead of 0.2
    subs = ans[2:]  # ''  get an empty string rather than '2'
    subs[0]         # IndexError: string index out of range    
    

    reference: http://www.informit.com/articles/article.aspx?p=1439189 (see 'True division' part) and https://www.python.org/dev/peps/pep-0238/

    You might need to change ans = str(numerator/denominator) to ans = str(numerator/float(denominator)) to force true division in python 2.

    2.The current supported version of python is python 2.7.8 , according to Frequently Asked Questions

    Languages	 Version
    C++	         g++ 4.9.1
    Java	     java 1.8.0_25
    Python	     python 2.7.8
    MySQL	     mysql-server 5.5.40
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.