如何从大数字“剪切”偶数序列?

时间:2014-03-02 18:55:58

标签: python sequence

我的程序应该执行以下操作:

  • 获取大数字偶数序列的最大长度
  • 获取序列开头的索引并获取序列本身,
  • 如果没有偶数打印无

该程序的大多数部分都在工作,但很少有错误,例如:

>>>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)

2 个答案:

答案 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']

这是你想要的吗?