我正在尝试生成 morris sequence在 python 。我目前的解决方案如下,但我觉得我只是用 python 编写了 c。谁能提供更 pythonic 的解决方案?
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)]
最佳答案
itertools.groupby
似乎非常适合!定义一个 next_morris
函数如下:
def next_morris(number):
return ''.join('%s%s' % (len(list(group)), digit)
for digit, group in itertools.groupby(str(number)))
就是这样!!!看:
print next_morris(1)
11
print next_morris(111221)
312211
我可以用它来制作发电机:
def morris_generator(maxlen, start=1):
num = str(start)
while len(num) < maxlen:
yield int(num)
num = next_morris(num)
用法:
for n in morris_generator(10):
print n
结果:
1
11
21
1211
111221
312211
13112221
关于python - 任何人都可以提供一种更 pythonic 的方式来生成莫里斯序列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/553871/