简体   繁体   English

如何优化此Python代码?

[英]How do I optimise this Python code?

I'm doing a coding challenge for fun and to work on my skills - some of you may remember the Advent of Code challenge from last December, I'm working through that. 我正在做一个有趣的编码挑战,并努力提高自己的技能-你们中的一些人可能还记得去年12月的代码问世挑战,我正在努力。 I've got this code as the solution to one of the problems, which works, but it's uselessly slow. 我已经获得了这段代码作为对其中一个问题的解决方案,该方法可以正常工作,但是它的速度很慢。

inp = "1113122113"

def iterate(num):
    pos = 0
    new = ""
    while pos < len(num):
        counter = 0
        d = num[pos]
        for i in range(pos, len(num)):
            if num[i] == d:
                counter += 1
            else:
                break
        new+=str(counter)
        new+=str(d)
        pos += counter
    print len(new)
    return new

for i in range (50):
    inp = iterate(inp)

Past iteration 35 or so, it gets to the point where it's taking several minutes for each iteration. 经过约35次迭代后,每次迭代都需要花费几分钟。 The object is to generate a look-and-say sequence - so 1 goes to 11, then 21, 1211, 111221, 3112211 and so on. 目的是生成一个外观序列-因此1进入11,然后是21、1211、111221、3112211,依此类推。 I need to find the length of the string after the 50th iteration, but it's 360154 characters long after 40 iterations and my code just isn't optimised enough to handle strings that long in a reasonable time. 我需要在第50次迭代后找到字符串的长度,但是经过40次迭代后,它的长度为360154个字符,而我的代码还不够优化,无法在合理的时间内处理那么长的字符串。 Can anyone give me some pointers? 谁能给我一些指导?

Using itertools.groupby will make this very fast. 使用itertools.groupby将使此过程非常快。

from itertools import groupby
def next_say(s):
    return ''.join(str(sum(1 for _ in g))+k for k, g in groupby(s))

def iterate(num):
    """Generator that yields the first num iterations"""
    val = '1'
    for i in range(num):
        val = next_say(val)
        yield val

https://docs.python.org/2/library/itertools.html#itertools.groupby https://docs.python.org/2/library/itertools.html#itertools.groupby

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM