2

我必须从用户那里获得两个正整数(一个长一个短)。然后我必须遍历较长的整数(从左到右)并检查较短的整数是否出现在较长的整数内。我必须报告比赛的位置和比赛的数量。

*我不允许使用字符串和列表来执行此操作):

# Ask user for positve longer integer number
import math

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
longLength = int(math.log10(longInt)) + 1
shortLength = int (math.log10(shortInt)) + 1

for offset in range(longLength):
    subInt = longInt // 10 ** offset % 10 ** shortLength
    print(subInt)
    if subInt == shortInt:
        print("Found a match at position ", offset)

所以我得到的结果是:

Input a positive longer integer: 123456
Input a positive shorter integer: 12
56
45
34
23
12
Found a match at position  4
1

但是如何让它long_int从左到右而不是从右到左循环呢?像这样:

Input a positive longer integer: 123456
Input a positive shorter integer: 12

1
12
Found a match at position  1
23
34
45
56

请帮忙!谢谢!

4

1 回答 1

3

减去offsetfromlongLength以“向后”计数:

for offset in range(longLength):
    subInt = longInt // 10**(longLength - offset - 1) % 10**(shortLength)
于 2013-10-02T07:36:55.173 回答