How to find out if a number is subnumber

Asked

Viewed 574 times

2

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

Soon P is sub number of Q. Grateful from now on.

2 answers

3

A simple way to do it:

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

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

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

str(P) in str(Q)
  • Wow,had made a code with more than 20 lines,much more complicated.

  • Thank you very much, it’s very helpful.

2

With the method find you can check if occurrences in the string target, see the example below:

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

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

Variable implementation:

P = '101'
Q = '100001010057'

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

Hare up that method find is a module method string py. that is, it only works with strings, if you have an integer you will need to convert it to string as in the example above.

Source: https://docs.python.org/2/library/string.html

  • If you don’t understand something, leave a comment and I’ll add more information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.