的Python 2.x版(目前還不清楚你想要哪一個):
from __future__ import print_function
import sys
even = '02468' # even = ''.join(range(0,10,2))
# in python 2.x is very unsafe and unreliable, use raw_input
answer = raw_input('Please enter a positive integer: ')
# in python 3.x you can use input(), but just cast it to desired
# type and catch errors with 'except ValueError:' clause or...
# check here if all characters are digits:
if not answer.strip().isdigit():
print ("Wrong input.")
sys.exit(1)
sequence = answer
# this returns number of consecutive even digits
def even_len(sequence):
for i, digit in enumerate(sequence):
if digit not in even:
return i # early break on the first odd digit
return i
start, length = 0, 0
i, n = 0, len(sequence)
while i < n:
this_len = even_len(sequence[i:]) # search for rest of input
if this_len > length:
length = this_len
start = i
i += this_len + 1 # let's skip already checked digits
print("The maximal length is", length)
print("Sequence starts at", start)
print("Sequence is", sequence[start : start+length])
什麼錯誤?你能詳細說明嗎? –