細節:
有兩個字串
x和y。數
occurrence of y in x如下:y 的長度為 3。
增加“計數”值時
y == x[i] x[i 2] x[i 4]
例子:
x = "aabbcc"
y = "abc"
output: 2
我的代碼:
def solution(x, y):
i, count = 0, 0
j = i 2
k = i 4
while i 4 < len(x):
cur = x[i]
while i < len(x) and i != j:
i = 1
while i < len(x) and i != k:
i = 1
count = 1
return count
solution(x, y)
我越來越count = 1。它應該給count = 2
uj5u.com熱心網友回復:
您的代碼中有幾個邏輯錯誤。
問題發生在這里:
while i < len(x) and i != j:
i = 1
res.append(x[i])
您不斷增加,i直到len(x)它等于或大于 ,或者直到它與 相同j。但是由于您設定j為2開始(并且永遠不會更新它),它最終只會設定i為len(x). 因此x[i]會失敗,因為x[len(x)]試圖在x.
但是,還有幾點需要說明:
- 你收集你找到的東西
res,但實際上只想要一個數字(例如2)作為結果 - 你定義
count但不使用它 - 您在三個單獨的變數(
i,j,k)中跟蹤字串中的坐標,并且有很多邏輯來增加第一個變數,但實際上您需要的只是一次遍歷一個位置的字串,并直接查看偏移量
鑒于所有這些和問題描述,您可能會這樣做:
x = "aabbcc"
y = "abc"
def solution(x, y):
i, count = 0, 0
while i 4 < len(x):
if (x[i], x[i 2], x[i 4]) == (y[0], y[1], y[2]):
count = 1
i = 1
return count
print(solution(x, y))
然而,Python 有一些聰明之處可以使它更簡單(或至少更短):
def solution(x, y):
count = 0
for i in range(len(x)-4):
if x[i:i 5:2] == y: # slicing with a stride of two, instead of direct indexing
count = 1
return count
甚至:
def solution(x, y):
return len([x for i in range(len(x)-4) if x[i:i 5:2] == y])
但我覺得這有點過于簡潔而不是可讀性。
uj5u.com熱心網友回復:
生成器運算式解決方案,True/False == 1/0在數字背景關系中利用:
def solution(x, y):
return sum(y == x[i:i 5:2] for i in range(len(x)-4))
uj5u.com熱心網友回復:
當 y == x[i] x[i 2] x[i 4] 時增加“計數”值
這與簡單地創建由x[0], x[2], x[4]...(每個偶數字符)組成的字串和由x[1], x[3], x[5]...(每個奇數字符)組成的字串是一樣的;計算y每個中的出現次數;并將這兩個結果加在一起。
創建字串是微不足道的,并且是常見的重復。計算子串的出現次數也很常見。將這些工具放在一起:
def spread_substrings(needle, haystack):
even_haystack = haystack[::2]
odd_haystack = haystack[1::2]
return even_haystack.count(needle) odd_haystack.count(needle)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510112.html
