2013-07-09 126 views
1
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:]) 

这是我到目前为止所。简单的代码,试图查看一个字符串是否符合以下条件。 然而,当我进行检查(S)我得到:IndexError串索引超出范围

True 
IndexError: string index out of range 

任何帮助吗?预先感谢 编辑:如果字符串只包含单个数字,则函数的目的是生成true;如果字符串中存在两个或更多个数字,则为false。

+1

究竟是什么你想在这里做什么? –

+0

@AshwiniChaudhary函数的目的是在字符串只包含单个数字的情况下生成true,如果字符串中存在2个或更多的数字,则为false。 – user2562952

回答

3

n的长度为0时,n[0]部分将因为空字符串而引发错误。您应该在那里添加return声明而不是打印。

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

注意,条件必须是len(n) < 2否则你会在n[1]得到一个错误,当字符串的长度为1

其次你要匹配字符包含整数的列表,所以检查总是会是False。将列表项目转换为字符串或更好地使用str.isdigit

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

更新:

您可以使用regexall此:

>>> 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 

工作代码的版本:

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))") 

输出:

True 
False 
+0

好的答案,除了我认为你的意思是说,如果len(n)<1,那么你会回来。这样,如果你留在函数中(不返回),你知道len(n)必须> = 1。 –

+0

@DaveLillethun你是对的,修正它。 –

+0

@AshwiniChaudhary对不起,我不熟悉在这个论坛上回复。 http://puu.sh/3yqfF.png这是我的修改代码的图像。我基本上试图查看一个字符串是否只有一个数字 – user2562952

1

您应该在第一个if语句后执行return True,而不是print True。该函数继续在语句后运行,并在输入大小为0时触发错误。

0

我无法重现你的错误。

我不得不修复的几件事情:

  • 压痕,我猜只是一个问题,粘贴到网页
  • .isdigit()是一个函数;调用.isdigit==True将比较一个函数对象与True,这永远不会是真的。我将.isdigit==True更改为.isdigit()
  • 我确保返回值冒泡 - 没有这个,递归完成了,但最外层的函数只是返回“无”。

除此之外,一些打印报表显示,这是按预期工作

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) 

输出:

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