序列计算问题

时间:2014-03-01 21:00:35

标签: python numbers

我试图计算一个数字中偶数位的最大长度,并打印序列开头的索引和序列本身。

这是我开始使用的代码,但它有一些错误:

num = int(eval(input("Please enter a positive integer: ")))

length=0
seq=None
start = -1
while num!=0:
     d = num % 2
     num = num /10
     if d==0:
        length=length+1


print("The maximal length is", length)
print("Sequence starts at", start)
print("Sequence is", seq)}

3 个答案:

答案 0 :(得分:0)

我想你会看到一个NameError例外(但我不应该:当你报告代码问题时,报告其行为也很重要,不要只说“它不是工作“因为有一百万种方法可能会失败”。 [注意:我怀疑这只是因为代码被格式化系统破坏了,所以我假设你确实在num]中读了一个数字。

只在开始时找到跑步是否可以接受? 345666678怎么样?您目前在代码中没有任何内容可以向前移动起点。但是你的代码显示了许多正确的想法,所以让我们讨论算法的策略应该是什么。

由于数字中可能存在多次运行,因此任务将减少为查找所有运行并选择最长运行。因此,首先将longest_run设置为零,如果数字仅包含奇数位,则应保留该值。

当您找到一个奇数位(字符串末尾的)时,将当前run_lengthlongest_run进行比较,如果更长则将其替换(必须是运行结束,即使运行长度为零)然后将run_length设置回零。当您找到偶数时,请在run_length添加一个。

你似乎是一个初学者,所以祝贺你能够解决问题的这么多要素。

答案 1 :(得分:0)

一个简单的解决方案可能如下:

a = int(eval(input("Please enter a positive integer: ")))
# Items in the sequence to look for
even = ['0','2','4','6','8']
# Length of the current sequence
le = 0
# and starting position
st = -1
# Length of the longest sequence
maxLe = 0
# and starting position
maxSt = -1

# Loop through the digits of the number
for idx,num in enumerate(str(a)):
    if num in even:
        le += 1
        if le == 1:
            # If it is a new sequence, save the starting position
            st = idx
    else:
        # If there are no more even digits, check if it is the longest sequence
        if le > maxLe:
            maxLe = le
            maxSt = st
        # Reset to look for the next sequence
        le = 0

答案 2 :(得分:0)

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