我的程序应该执行以下操作:
该程序的大多数部分都在工作,但很少有错误,例如:
>>>Please enter a positive integer: 2300245
>>>The maximal length is 0
>>>Sequence starts at 2
>>>Sequence is []
这是我的代码:
num = int(input("Please enter a positive integer: "))
length=0
seq=[None]
start = -1
maxlength=0
maxstart=-1
even=['0','2','4','6','8']
for index,i in enumerate(str(num)):
if i in even:
length+=1
if length==1:
start=index
seq+=[i]
else:
if length>maxlength:
maxlength=length
maxstart=start
seq=[]
length=0
print("The maximal length is", length)
print("Sequence starts at", start)
print("Sequence is", seq)
答案 0 :(得分:0)
当您在字符串中看到新值时,您将seq
设置为空。与将长度保存为maxlength
的方式相同,您还应将序列保存在变量中,因为您在seq
的同时重置了length
。
答案 1 :(得分:0)
seq = []
start = -1
num = int(input("Please entrer a positive integer: "))
for idx, value in enumerate(str(num)):
# Test if value is even
if int(value) % 2 == 0:
if len(seq) == 0:
start = idx
seq.append(value)
print "The maximal length is %i" % len(seq)
print "Sequence starts at %i" % start
print "Sequence is %s" % seq
甚至,使用列表理解:
num = int(input("Please entrer a positive integer: "))
seq = [value for value in str(num) if int(value) % 2 == 0]
start = str(num).index(seq[0]) if len(seq) > 0 else -1
print "The maximal length is %i" % len(seq)
print "Sequence starts at %i" % start
print "Sequence is %s" % seq
此代码返回:
Please entrer a positive integer: 256387456
The maximal length is 5
Sequence starts at 0
Sequence is ['2', '6', '8', '4', '6']
这是你想要的吗?