计算最大的偶数序列数量
我想要计算我输入的数字中,最长的连续偶数数字的序列,找出它的索引和这个偶数序列本身。
我刚开始学习编程,所以现在还在构思阶段,这是我想到的:
Split the number to a list of single digits.
Apply modulo 2 to all digits.
Count where is the biggest sequence of zeros.
Take its index.
From the index extract the original from the starting number.
我现在的问题是 str.split() 这个函数,它的作用是去掉分隔符,我还得指定所有10个数字才能让它把每个数字分开。
有没有其他的函数可以满足我第一步的需求,还是我需要再想想?
备注:我使用的是 Python 3.2。
3 个回答
1
我觉得你想要的东西是 list()
nums = 1423341
list(str(nums))
=> ['1', '4', '2', '3', '3', '4', '1']
因为你说你刚开始学习,使用一些基本的方法来完成你想做的事情,可能会比使用更复杂的东西,比如 lambda 函数,要简单得多。
2
我不能对thefourtheye的代码发表评论,但它在处理像这样的数字时是无效的:
nums = str(155555555344444442)
或者:
nums = str(155555555)
我找到了一种简单的方法,使用了re模块。它可以返回所有相同长度的序列。
import re
nums = str(22554442266)
groups = sorted([(len(n.group(0)), n.group(0), n.span(0)[0]) for n in re.finditer('(\d)\\1+', nums)], reverse=True)
results = [(groups[0][1], groups[0][2])] # Sequence, index
for n in groups[1:] :
if n[0] != groups[0][0] :
break
results.append((n[1], n[2]))
print(results) # => [('444', 4)]
# nums = str(1112255566622111) => [('666', 8), ('555', 5), ('111', 13), ('111', 0)]
# nums = str(1112222333) => [('2222', 3)]
3
在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。比如,有人可能会在使用某个功能时,发现它的表现和预期不一样。这种情况可能是因为我们没有正确理解这个功能的用法,或者是因为我们在使用时犯了一些小错误。
为了帮助大家更好地理解这些问题,很多人会在网上提问,比如在StackOverflow上。他们会详细描述自己遇到的情况,提供相关的代码示例,并询问其他人是否遇到过类似的问题,或者有没有解决方案。
通过这样的交流,大家可以互相学习,找到解决问题的方法。记住,编程是一个不断学习和实践的过程,遇到问题是很正常的,关键是要积极寻求帮助和解决方案。
nums = str(12344444442)
from itertools import groupby as gby
if all (int(num) % 2 for num in nums):
print("All are Odd numbers")
else:
m_list=max((list(g) for n,g in gby(nums,key=lambda x:int(x)%2) if not n),key=len)
# ['4', '4', '4', '4', '4', '4', '4', '2'] Longest even sequence
print(nums.index("".join(m_list)))
# 3 Starting index