Python检查匹配数字

时间:2013-09-25 03:11:40

标签: python pattern-matching

我正在尝试检查short int是否包含long int中包含的数字。取而代之的是:

long int: 198381998
short int: 19
Found a match at   0
Found a match at   1
Found a match at   2
Found a match at   3
Found a match at   4
Found a match at   5
Found a match at   6
Found a match at   7

假设看起来像这样:(正确的)

long int: 198381998
short int: 19
Found a match at   0
Found a match at   5

代码:

longInt = ( input ("long int: "))
floatLong = float (longInt)
shortInt =  ( input ("short int: "))
floatShort = float (shortInt)

max_digit =  int (math.log10(floatLong)) #Count the no. of long int

i = int(math.log10(floatShort)) # Count the no. shortInt that is being input


for string in range (max_digit):

    if ( shortInt in longInt): # Check whether there is any digit in shortInt 
                               # that contains anything inside longInt
        print ( "Found a match at  ", string)

不使用python的任何内置函数,没有list或string.etc方法。

2 个答案:

答案 0 :(得分:0)

shortInt in longInt始终为True('19' in 198381998'始终为True)。

使用切片:

>>> '198381998'[4:6]
'81'
>>> '198381998'[5:7]
'19'

long_int = input("long int: ")
short_int =  input("short int: ")

short_len = len(short_int) # You don't need `math.log10`

for i in range(len(long_int)):
    if long_int[i:i+short_len] == short_int:
        print("Found a match at", i)

答案 1 :(得分:0)

在数字位置的循环中,通过使用整数%(除法的余数,也就是模数),//(整数除法)和**(提升幂)来制作“整数切片”函数)操作。这是一个想法:

>>> l = 1932319
>>> l // (10**3) % (10**2)
32

然后你可以将它与你的小整数(使用通常的==)进行比较。剩下的就是你的作业,我想。

NB。 'in'操作是字符串操作,因此您无法使用它。