计算最大的偶数序列

时间:2014-03-03 13:12:51

标签: python python-3.x

我想计算I输入数字中偶数位的最大序列,找到它的索引和偶数位序列本身。

我只是开始学习编程,所以我只是在草图阶段,这就是我的想法:

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 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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)]

答案 2 :(得分:1)

我认为你要找的是list()

nums = 1423341
list(str(nums))
=> ['1', '4', '2', '3', '3', '4', '1']

既然你说你刚刚开始,使用基本方法来做你想做的事情可能比使用lambdas等等更好。

相关问题