の長さn
が 0の場合n[0]
、文字列が空であるため、パーツでエラーが発生します。return
印刷する代わりにステートメントを追加する必要があります。
def checker(n):
if len(n) < 2:
return True
if n[0] in x:
そうしないと、文字列の長さが 1 のときにlen(n) < 2
エラーが発生します。n[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