【问题标题】:How to loop through an integer and extract another shorter integer (from left to right)?如何遍历一个整数并提取另一个较短的整数(从左到右)?
【发布时间】:2013-10-08 13:05:47
【问题描述】:

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

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

# 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

请帮忙!谢谢!

【问题讨论】:

  • 我不允许使用字符串和列表来执行此操作。哦,你不喜欢任意的家庭作业限制。
  • @MartijnPieters,是的。所以bytearray是允许的:)
  • @gnibbler:元组也是如此!
  • @MartijnPieters,但您不能只将 in 用于元组

标签: python math python-3.x integer


【解决方案1】:

longLength 中减去offset 以向后计数:

for offset in range(longLength):
    subInt = longInt // 10**(longLength - offset - 1) % 10**(shortLength)

【讨论】:

  • 我无法识别语法。这是什么语言?
  • @MMss:嗯,看看问题上的标签?它是 Python。
  • 准确地说是 Python 3 —// 通常不会在 Python 2 代码中找到,这可能就是造成混淆的原因。
  • 感谢@MartijnPieters! (: 你知道我怎样才能用 '12' 而不是 '1' 开始结果 subInt 吗?
  • @JanL:减去shortLength 而不是1,并调整您的range() 以循环到range(longLenth - shortLength + 1)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 2013-10-06
相关资源
最近更新 更多