当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
更新:
您可以使用regex
和all
此:
>>> 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
究竟是什么你想在这里做什么? –
@AshwiniChaudhary函数的目的是在字符串只包含单个数字的情况下生成true,如果字符串中存在2个或更多的数字,则为false。 – user2562952