按升序排列的数字作为字符串输入。程序应该打印缺少的数字?
import re
input_str='{name:robert,surname:paul}'
output_str=re.sub(r':(\w*)', r':"\1"', input_str )
print output_str
我的代码
{name:"robert",surname:"paul"}
我的查询:
如果以字符串形式输入2位或4位数字,我的程序无法找到丢失的号码。
EX:
INPUT
567568600601602
OUTPUT
569
EXPLANATION
567,568,600,601,602 are the numbers in sequence and 569 is the missing number
INPUT
1112131516
OUTPUT
14
EXPLANATION
11,12,13,15,16 are the numbers in sequence and 569 is the missing
如何检查字符串是否有2位或3位或4位数字并相应地将它们分开?
答案 0 :(得分:2)
使用伪代码评估算法。确定重要概念并使用参数创建函数。给出有意义的名字用铅笔和纸运行迭代。如果它工作,改进算法。确定支持您的用例的数据结构。
目前的代码不是针对人眼,而是要求人们寻求帮助。
答案 1 :(得分:1)
我只是为了好玩而采用这种方法,它似乎有效(我不能控制错误的输入异常,它肯定可以改进)。我基本上从1个字符长度开始,如果我是对的,请尝试。
我希望它有所帮助:
MAX_LEN = 6
def findMissingNumber(s):
print 'Input received: ' + s
for digitsNumber in range(1,MAX_LEN+1):
print
# Initializing stuff
index = digitsNumber
currentNumber = int(s[:digitsNumber])
exit = False
missing = None
while not exit and index < len(s):
# Store expected next number
nextNumber = currentNumber + 1
# Store expected next number length
nextNumberLen = len(str(nextNumber))
# Store next number in the provided string
# based the lenght of the expected number
nextStringNumber = int(s[index : index + nextNumberLen])
print 'Have ' + str(currentNumber) + ', expecting ' + str([nextNumber,nextNumber+1]) + ' and got ' + str(nextStringNumber)
# Check if number gotten is the next or the following
if nextStringNumber in [nextNumber, nextNumber+1]:
# Check if number is not the next
# (means there is a number missing)
if nextStringNumber != nextNumber:
# Check if there was a previous missing number
if not missing:
print 'Found missing ' + str(nextNumber)
missing = nextNumber
# If there was, exit and forget missing number
# (only 1 missing number allowed)
else:
print 'More than 1 missing, exit'
missing = None
exit = True
# Set stuff for next iteration
currentNumber = nextStringNumber
index += nextNumberLen
# If end of string, exit
else:
print 'End of string, exit'
exit = True
# If only 1 missing found, return it
if missing:
print 'Returning ' + str(missing)
return missing
print 'Going to next number lenght'
# If no missing found, return -1
return -1
findMissingNumber('6768707172')
作出结果:
Input received: 6768707172
Have 6, expecting [7, 8] and got 7
Have 7, expecting [8, 9] and got 6
End of string, exit
Going to next number lenght
Have 67, expecting [68, 69] and got 68
Have 68, expecting [69, 70] and got 70
Found missing 69
Have 70, expecting [71, 72] and got 71
Have 71, expecting [72, 73] and got 72
Returning 69