-2

我正在尝试检查短整数是否具有包含长整数的数字。取而代之的是:

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 方法。

4

2 回答 2

0

在您的数字位置循环中,通过使用整数%(除法的余数又称为模数)、//(整数除法)和**(升幂)操作来实现“整数切片”功能。这是想法:

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

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

注意。'in' 操作是字符串操作,所以不能使用。

于 2013-09-25T03:36:39.813 回答
0

shortInt in longInt始终为真('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)
于 2013-09-25T03:23:00.920 回答