如何从两个不同的整数中提取短数字序列并进行比较?

2024-05-23 17:47:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我的一个作业遇到了麻烦。在

所以问题是: 我必须从用户那里得到两个正整数(一个长一个短)。然后,我必须遍历较长的整数(从左到右),并检查较短的整数是否出现在较长的整数中。我必须报告比赛的位置和数量。
*我不允许使用字符串和列表来完成此分配):

结果的例子应该是这样的:

例1。
输入一个正长整数:123456789
输入一个正的短整数:123
在位置0找到匹配项
结束:找到1个匹配项

例2.
输入一个正长整数:123456789
输入一个正的短整数:789
在位置6找到匹配项
结束:找到1个匹配项

例3.
输入一个正的长整数:12312312312231222
输入一个正的短整数:22
在位置10找到匹配项
在14位找到匹配项
在位置15找到匹配项
结束:找到3个匹配项

例4.
输入一个正的长整数:12312312312231222
输入一个正的短整数:55
结束:找不到任何匹配项

到目前为止我所做的:

# Ask user for positve longer integer number
longInt = int(input("Input a positive longer integer: "))

# Ask user for positive shorter integer number 
shortInt = int(input("Input a positive shorter integer: "))

# Count number of digits in both longer and shorter integer numbers
import math
longLength = int(math.log10(longInt))+1
shortLength = int (math.log10(shortInt))+1

for i in range(0,longLength):
    for x in range(0,shortLength):
        while (longLength > 0):
            longDigit = longInt % 10 **(longLength) // 10**(longLength-1)
            longLength-=1
            print (longDigit)
        while (shortLength > 0):
            shortDigit = shortInt % 10**(shortLength) // 10**(shortLength-1)
            shortLength-=1
            print (shortDigit)

请帮忙!谢谢!(:


Tags: innumberfor整数mathintegeraskint
2条回答

您只需将longInt偏移几次,就可以提取出所有短整型长度的整数(比如位移位,但是使用十的幂次而不是2)。在

import math

# Ask user for positve longer integer number
longInt = 123456789 

# Ask user for positive shorter integer number 
shortInt = 1234

# Count number of digits in both longer and shorter integer numbers

longLength  = int( math.log10(longInt) )+1
shortLength = int( math.log10(shortInt))+1

for offset in range(0, longLength):
  subInt = (longInt// 10**(offset)) % 10 **(shortLength) 
  print(subInt)

结果:

6789 5678 4567 3456 2345 1234 123 12 1

你可以按照以下思路做些事情:

def i2l(i):
    rtr=[]
    while i:
        rtr.insert(0, i%10)
        i//=10
    return rtr

longer=int(input("Input a positive longer integer: "))    
shorter=int(input("Input a positive shorter integer: "))

ll=i2l(longer)   
ls=i2l(shorter)

answer=[]
for idx in [i for i,e in enumerate(ll) if e==ls[0]]:    
    try:
        all_good=all(ll[i+idx]==e for i,e in enumerate(ls))    
    except IndexError:
        all_good=False 
    if all_good:
        answer.append(idx)

if answer:
    s='index' if len(answer)==1 else 'indices'
    print '{} found in {} at {} {}'.format(shorter,longer,s,answer)
else:
    print '{} not found in {}'.format(shorter,longer) 

现在运行它:

^{pr2}$

相关问题 更多 >