Is there a way to find if an integer occurs in another integer? For example if two integers A and B are given. Integer A occurs in Integer B at position P then the leftmost position should be returned.
For example, 53 occurs in 1953786 at position 2, so the function should return 2.
Convert both to strings:
b = 1953786
a = 53
str(b).index(str(a))
# 2
Note this finds the first occurrence only, if there are multiple.
Two possible bumps in the road as pointed out by @user2357112:
The search isn't linear time. The runtime characteristics are quite complicated - it's better than linear if some of the speed tricks the implementation uses work out, and quadratic in the bad cases. [quoting directly there]
In the quadratic-time scenario, str() constructor itself will run into trouble for very large ints.
I misunderstood the original question. If you want to know all the occurrences rather than just first, you can do:
import re
a=1553545355343
b=53
all_ocurrences = [m.start() for m in re.finditer(str(b), str(a))]
print(all_ocurrences)
#[2, 6, 9]
If you care for just the first left most position, you can go for Brad's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With