Subset a large number into smaller series of numbers using python

I have a big number lets say of around hundred digits. I want to subset that big number into consecutive number of 5 digits and find the product of those 5 digits. For example my first 5 digit number would be 73167. I need to check the product of the individual numbers in 73167 and so on.

The sample number is as follows:

73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557

I have a problem subsetting the small numbers out of the big number.

My basic starting code is :

b = 73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557
jd = str(b)
for ch in jd:
    number = ch
    print (number)

Any help is highly appreciated.


Edit: I believe that grouper is overkill in this solution, look at the solution by @Haidro https://stackoverflow.com/a/16078696/1219006


Using the grouper recipe from itertools

I'm assuming b is a string to begin with because it would be a crazy waste of memory to make a number that big.

from itertools import izip_longest
from operator import mul

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

for g in grouper(5, b, fillvalue=''):
    # And to work out the product of the digits
    num = ''.join(g)
    prod = reduce(mul, map(int, num))

尝试这个:

from operator import mul
def chunker(seq, size):
    return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
for i in chunker(str(myint),5): # Where myint is that big number
    reduce(mul, map(int, i))

一行为你:

import re; re.findall("d{5}", number)             
链接地址: http://www.djcxy.com/p/55128.html

上一篇: Python uuid4,如何限制Unique字符的长度

下一篇: 使用python将大量数据转换为更小的一系列数字