字符串的優度遵循以下兩個規則:澄清簡單的函數
- 字符串的包含一個或多個優度「U的是0
- 否則,一個字符串的善良等於數的的「g'的字符串中
「gbbgb」 爲2
「gubgb」 是0
#I understand this function
def goodness(s):
if s.count('u') > 0:
return 0
else:
return s.count('g')
#But not this one.
def best_slice(s, k):
''' s is str, k is an integer such that 0 <= k <= len(s). Return the starting index of the length-k slice of s with highest goodness. If k is zero, return -1.'''
stop = len(s) - k # ?
best_start = -1 # ?
best_goodness = 0
for i in range(stop + 1):
cur_slice = s[i:i+k]
slice_goodness = goodness(cur_slice)
if slice_goodness > best_goodness:
best_start = i
best_goodness = slice_goodness
return best_start
有人可以爲我解釋這個,我不明白。
什麼部分你不明白? –