'Check how many times a number appears within another without strings or lists (Python)
I need to find how many times a number appears within another, for example, if I need to find how many times 22 appears of 2228, I need my output to be 1, or if I want to find 12345 in 1234 it must be 0. I can't use either lists or strings, only if and while.
This is my code so far:
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))
Solution 1:[1]
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
For example for 22 and 2228, this first computes mod = 100 to always give us the last two digits of numB. Then:
2228 % 100is28. Doesn't match, so drop the8and continue with222.222 % 100is22. Matches, so drop the22and continue with2.2 % 100is2. Doesn't match, so drop the2and continue with0.- Actually, don't continue, at
0we stop.
Passes all your tests as well as these:
for a in range(1000):
for b in range(10000):
expect = str(b).count(str(a))
result = contarApariciones(a, b)
assert result == expect
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pychopath |
