[英]How to find the number of times an item appears in a list of list of strings without using counter, or dictionary in python?
[英]Check how many times a number appears within another without strings or lists (Python)
我需要查找一個數字在另一個數字中出現了多少次,例如,如果我需要查找 22 在 2228 中出現了多少次,我需要我的 output 為 1,或者如果我想在 1234 中找到 12345,則它必須為 0 . 我不能使用列表或字符串,只有當和同時。
到目前為止,這是我的代碼:
def contarApariciones (numA, numB):
count = 0
while numB != 0:
digA = numA % 10
digB = numB % 10
position = 1
searchedN = 0
while searchedN != numA:
if digB == digA:
cuenta +=1
searchedN = digA + position
posicion *= 10
numB // 10
return count
else: numB // 10
print (contarApariciones(22,2228))
#output 1
print (contarApariciones(12345,1234))
#output 0
print (contarApariciones(808,80808808))
#output 2
print (contarApariciones(1,10111010))
#output 5
print (contarApariciones(0,0))
def contarApariciones(numA, numB):
if numA == 0 == numB:
return 1
count = 0
mod = 10
while mod <= numA:
mod *= 10
while numB:
if numB % mod == numA:
count += 1
numB //= mod
else:
numB //= 10
return count
例如,對於22
和2228
,這首先計算mod = 100
以始終為我們提供numB
的最后兩位數字。 然后:
2228 % 100
是28
。 不匹配,所以刪除8
並繼續222
。222 % 100
是22
。 匹配,所以刪除22
並繼續2
。2 % 100
是2
。 不匹配,所以刪除2
並繼續0
。0
處停止。通過所有測試以及這些測試:
for a in range(1000):
for b in range(10000):
expect = str(b).count(str(a))
result = contarApariciones(a, b)
assert result == expect
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.