Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if an integer occurs in another integer

Tags:

python

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.

like image 492
DENDULURI CHAITANYA Avatar asked Dec 11 '25 04:12

DENDULURI CHAITANYA


2 Answers

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:

  1. 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]

  2. In the quadratic-time scenario, str() constructor itself will run into trouble for very large ints.

like image 198
Brad Solomon Avatar answered Dec 13 '25 18:12

Brad Solomon


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.

like image 31
A Monad is a Monoid Avatar answered Dec 13 '25 17:12

A Monad is a Monoid