首先,儘量避免這樣的代碼:
if Action():
lots of code
return True
return False
翻轉,所以大部分代碼不是嵌套的。這給了我們:
def check(isbn):
check_digit = int(isbn[-1])
match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1])
if not match:
return False
digits = match.group(1) + match.group(2) + match.group(3)
result = 0
for i, digit in enumerate(digits):
result += (i + 1) * int(digit)
return True if (result % 11) == check_digit else False
有在代碼中的一些錯誤:
所以,讓我們簡化這一點。首先,刪除所有空格和連字符,並確保正則表達式匹配整行,方法是在'^ ... $'中進行支持。這可以確保它拒絕太長的字符串。
def check(isbn):
isbn = isbn.replace("-", "").replace(" ", "");
check_digit = int(isbn[-1])
match = re.search(r'^(\d{9})$', isbn[:-1])
if not match:
return False
digits = match.group(1)
result = 0
for i, digit in enumerate(digits):
result += (i + 1) * int(digit)
return True if (result % 11) == check_digit else False
接下來,我們來修復「X」校驗位問題。匹配正則表達式中的校驗位,因此整個字符串由正則表達式驗證,然後正確轉換校驗位。
def check(isbn):
isbn = isbn.replace("-", "").replace(" ", "").upper();
match = re.search(r'^(\d{9})(\d|X)$', isbn)
if not match:
return False
digits = match.group(1)
check_digit = 10 if match.group(2) == 'X' else int(match.group(2))
result = 0
for i, digit in enumerate(digits):
result += (i + 1) * int(digit)
return True if (result % 11) == check_digit else False
最後,使用生成的表達和max
是在Python做最後計算的更慣用的方式,最終的條件可以被簡化。如果你屬於isbn.org合規督察
def check(isbn):
isbn = isbn.replace("-", "").replace(" ", "").upper();
match = re.search(r'^(\d{9})(\d|X)$', isbn)
if not match:
return False
digits = match.group(1)
check_digit = 10 if match.group(2) == 'X' else int(match.group(2))
result = sum((i + 1) * int(digit) for i, digit in enumerate(digits))
return (result % 11) == check_digit
看起來不錯。我喜歡你使用切片。正如其他人指出的那樣,只需返回(結果%11)就可以簡化三元表達式。== check_digit – I82Much 2010-10-28 22:10:10
您也可以根據PEP8 –
2010-10-28 22:15:03
+1,因爲他們先做出傑出的工作,然後再問改進。做得好! – dotalchemy 2010-10-28 22:15:13