【发布时间】:2013-10-06 11:54:19
【问题描述】:
我是 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)
请帮忙!谢谢! (:
【问题讨论】:
-
感谢您说这是一项任务(很多人没有这样做的诚信)并发布所有可用信息。我不确定比较每个数字是否是最有效的解决方案:最好从 longInt 中提取子整数并将其与 shortInt 进行比较。
-
所以我不能使用while循环来循环longInt?因为如果我使用while循环,我有点卡在我必须放入两个整数的比较部分的地方,但是如果我不使用while循环,我不确定如何循环整数到提取数字。
-
你知道算术移位:en.wikipedia.org/wiki/Arithmetic_shift 吗?这是相同的方法,但有几十的幂。
标签: python integer compare python-3.3 digits