How to find out if a number is a sub-number

1

I would like a code, with explanation (if possible of course), to know if one number is sub number of another. Example:

  

P = 101
  Q = 100001010057

So P is sub number of Q . Thank you in advance.

    
asked by anonymous 27.02.2016 / 02:46

2 answers

3

A simple way to do this:

>>> str(101) in str(100001010057)
True

>>> str(18) in str(100001010057)
False

You convert your 2 numbers to string and use the in native Python operator, which looks for a substring within a string. More generic:

str(P) in str(Q)
    
27.02.2016 / 02:54
2

With the find method you can check for occurrences in the% target%, see the example below:

if '101'.find(str(011001101)): 
    print('101 eh sub numero de 011001101')

I converted to string the number string and then I searched the number 011001101 through the find method passing as a parameter the number sequence that is the target string that I converted.

Implementation with variables:

P = '101'
Q = '100001010057'

if P.find(Q):
    print("P eh sub numero de Q")

Make sure the 101 method is a method of the string.py module ie it only works with strings, if you have an integer you will need to convert it to string as it was done in the example above.

Source: link

    
27.02.2016 / 04:07