Can anyone provide a more pythonic way to generate morris sequences?

I am trying to create a morris sequence in python. My current solution is below, but I feel like I just wrote c in python. Can someone provide a more pythonic solution?

def morris(x):
    a = ['1', '11']
    yield a[0]
    yield a[1]
    while len(a) <= x:
        s = ''
        count = 1
        al = a[-1]
        for i in range(0,len(al)):
            if i+1 < len(al) and al[i] == al[i+1]:
                count += 1
            else:
                s += '%s%s' % (count, al[i])
                count = 1
        a.append(s)
        yield s
a = [i for i in morris(30)]
+5
source share
2 answers

itertools.groupbyIt seems perfect! Just define the function next_morrisas follows:

def next_morris(number):
    return ''.join('%s%s' % (len(list(group)), digit)
                   for digit, group in itertools.groupby(str(number)))

What all!!! Take a look:

print next_morris(1)
11
print next_morris(111221)
312211

I could use this to create a generator:

def morris_generator(maxlen, start=1):
    num = str(start)
    while len(num) < maxlen:
        yield int(num)
        num = next_morris(num)

Using:

for n in morris_generator(10):
    print n

results:

1
11
21
1211
111221
312211
13112221
+23
source
from itertools import groupby, islice

def morris():
    morris = '1'
    yield morris
    while True:
        morris = groupby(morris)
        morris = ((len(list(group)), key) for key, group in morris)
        morris = ((str(l), k) for l, k in morris)
        morris = ''.join(''.join(t) for t in morris)
        yield morris

print list(islice(morris(), 10))

, , . , , x, x ..

, , morris , - n := f(n-1).

, itertools, , geek ;) , .

, len() int, str. hickup - str.join), str.

, :

def morris(morris=None):
    if morris is None:
        morris = '1'
[...]

, :

def morris():
    morris = '1'
    yield morris
    while True:
        print morris
        morris = ''.join(''.join(t) 
                     for t in ((str(len(list(group))), key) 
                        for key, group in groupby(morris)))
        yield morris

, , , -, :

def m_groupby(s):
    for key, group in groupby(s):
        yield str(len(list(group)))
        yield key

def morris():
    morris = '1'
    yield morris
    while True:
        morris = ''.join(m_groupby(morris))
        yield morris

, !

+6

All Articles