![](/img/trans.png)
[英]Is there a bug in Codingbat practice: Warmup-2 > string_match? Or what is wrong in my code?
[英]Is there a simpler way to do string_match from CodingBat in Python?
這就是問題。 http://codingbat.com/prob/p182414
總而言之,給定兩個字符串(a 和 b),返回 2 的子字符串在字符串 b 中來自字符串 a 的次數。 例如,string_match('xxcaazz', 'xxbaaz') → 3。
def string_match(a, b):
amount = 0
for i in range(len(a)):
if (len(a[i:i+2]) == 2) and a[i:i+2] == b[i:i+2]:
amount += 1
return amount
不要太簡單了,但如果限制的范圍i
到len(a)-1
,你並不需要檢查它是否定義了足夠長串a
。
我的方法是這樣的:
def string_match(a, b):
count = 0
for i in range(len(a)-1):
if a[i:i+2]==b[i:i+2]:
count += 1
return count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.