Python 序列计算问题
我试图计算一个数字中偶数位数的最大长度,并打印序列开头的索引和序列本身 下面是我开始使用的代码,但它有一些bug:Python 序列计算问题,python,numbers,Python,Numbers,我试图计算一个数字中偶数位数的最大长度,并打印序列开头的索引和序列本身 下面是我开始使用的代码,但它有一些bug: 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 m
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)}
我想您会看到一个
namererror
异常(但我不必这样做:当您报告代码问题时,报告其行为也很重要,不要只说“它不工作”,因为它可能会失败的方式有一百万种)。[注意:我怀疑这只是因为代码被格式化系统弄乱了,所以我假设您确实在num
]中读取了一个数字
仅在开始时查找运行是否可以接受?345666678怎么样?您当前的代码中没有任何可以向前移动起点的内容。但是您的代码显示了许多正确的想法,所以让我们讨论一下算法的策略应该是什么
由于数量上可能有很多次运行,因此任务简化为查找所有运行并选择最长的运行。因此,首先将longest\u run
设置为零,如果该数字只包含奇数,则应保留该值
当您发现一个奇数(在字符串的末尾),将当前的运行长度
与最长运行长度
进行比较,如果更长,则将其替换(这必须是运行的结束,即使运行长度为零),然后将运行长度设置回零。找到偶数数字后,将其添加到行程长度中
您似乎是一名初学者,祝贺您纠正了问题中的许多要素。简单的解决方案如下:
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
Python2.x版本(不清楚您想要哪一个):
from\uuuuu future\uuuuu导入打印功能
导入系统
偶数='02468'#偶数=''.join(范围(0,10,2))
#在Python2.x中,使用原始输入是非常不安全和不可靠的
回答=原始输入('请输入一个正整数:')
#在Python3.x中,可以使用input(),但只需将其强制转换为所需的值
#使用“Exception ValueError:”子句或。。。
#如果所有字符都是数字,请选中此处:
如果没有,则回答.strip().isdigit():
打印(“输入错误”)
系统出口(1)
顺序=答案
#这将返回连续偶数位数
def偶数(顺序):
对于i,枚举中的数字(顺序):
如果数字不是偶数:
返回i#第一个奇数位的早中断
返回i
开始,长度=0,0
i、 n=0,len(序列)
而i
有哪些bug?你能详细说明一下吗?我不明白这部分:对于idx,枚举中的num(str(a)):idx和枚举是什么意思?如果你在循环中使用“枚举”,你会收到两个值:“索引”(或数组中的位置)和“值”,这是你在循环中通常使用的值。在任何情况下,如果这段代码有效,请选择我的答案并将问题标记为“已回答”。谢谢
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])