Search code examples
pythonwing-ide

IndexError string index out of range


s="(8+(2+4))"
def checker(n):
if len(n) == 0:
    return True
if n[0].isdigit==True:
    if n[1].isdigit==True:
        return False
    else:
        checker(n[1:])
else:
    checker(n[1:])

This is what I have so far. Simple code, trying to see if a string meets the following conditions. However when i perform checker(s) i get:

True
IndexError: string index out of range

Any help? Thanks in advance Edit: The function's purpose is to produce true if the string contains only single digit numbers, and false if 2 or more-figured digits exist in the string.


Solution

  • When the length of n is 0, the n[0] part is going to raise an error because the string in empty. You should add a return statement there instead of print.

    def checker(n):
        if len(n) < 2:
            return True
        if n[0] in x:
    

    Note that the conditions must be len(n) < 2 otherwise you'll get an error on n[1] when the length of string is 1.

    Secondly you're trying to match characters to a list which contains integers, so the in checks are always going to be False. Either convert the list items to string or better use str.isdigit.

    >>> '1'.isdigit()
    True
    >>> ')'.isdigit()
    False
    >>> '12'.isdigit()
    True
    

    Update:

    You can use regex and all for this:

    >>> import re
    def check(strs):
        nums = re.findall(r'\d+',strs)
        return all(len(c) == 1 for c in nums)
    ... 
    >>> s="(8+(2+4))"
    >>> check(s)
    True
    >>> check("(8+(2+42))")
    False
    

    Working version of your code:

    s="(8+(2+4))"
    def checker(n):
        if not n:           #better than len(n) == 0, empty string returns False in python
            return True
        if n[0].isdigit():  #str.digit is a method and it already returns a boolean value   
            if n[1].isdigit():   
                return False
            else:
                return checker(n[1:])  # use return statement for recursive calls
                                       # otherwise the recursive calls may return None  
        else:
            return checker(n[1:])        
    
    print checker("(8+(2+4))")
    print checker("(8+(2+42))")
    

    output:

    True
    False