user2562952
user2562952

Reputation: 27

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.

Upvotes: 1

Views: 1589

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250991

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

Upvotes: 3

James Polley
James Polley

Reputation: 8181

I can't reproduce your error.

I had to fix a few things:

  • Indentation, which I'm guessing was just a problem pasting into the page
  • .isdigit() is a function; calling .isdigit==True is going to compare a function object with True, which is never going to be true. I changed .isdigit==True to .isdigit()
  • I made sure return value gets bubbled up - without this, the recursion completes okay but the outermost function just returns "None".

Aside from that, a few print statements show that this is working as expected

s="(8+(2+4))"
t="(8+(20+4))"
def checker(n):
  print "checking %s" % n
  if len(n) == 0:
    print "Returning true"
    return True
  if n[0].isdigit():
    if n[1].isdigit():
        print "returning false"
        return False
    else:
        return checker(n[1:])
  else:
    return checker(n[1:])

print checker(s)
print checker(t)

Output:

checking (8+(2+4))
checking 8+(2+4))
checking +(2+4))
checking (2+4))
checking 2+4))
checking +4))
checking 4))
checking ))
checking )
checking 
Returning true
True
checking (8+(20+4))
checking 8+(20+4))
checking +(20+4))
checking (20+4))
checking 20+4))
returning false
False

Upvotes: 0

isaach1000
isaach1000

Reputation: 1839

You should do return True after the first if statement, not print True. The function continues to run after that statement and hits an error when the input is size 0.

Upvotes: 1

Related Questions