JP's Blog
Advent of Code 2015: Day 10
https://blog.jverkamp.com/2015/12/10/advent-of-code-day-10/
2015-12-10Part 1: Repeat a Look-and-say sequence 40 times. Return the length.
def look_and_say(seq):
result = ''
index = 0
count = 0
buffer = None
for c in seq:
if c == buffer:
count += 1
else:
if buffer:
result += '{}{}'.format(count, buffer)
count = 1
buffer = c
result += '{}{}'.format(count, buffer)
return result
def repeat(f, n, seq):
for i in range(n):
seq = f(seq)
return seq
print(len(repeat(look_and_say, int(sys.argv[2]), sys.argv[1])))
I’ve already gone into far more detail on Look and Say sequences before. But this time, we’re doing it iteratively in Python! Basically, we just maintain a bit of state for which character we are currently counting. When we change, output; otherwise, incrememnt the change.
There are some interesting tricks you could do with regular expressions, but I doubt you can find something faster or much more elegant than this.
Part 2: Repeat 50 times.
There’s nothing particular interesting about this one. I’ve already accounted for this by passing in the second paramter on the command line.
------------------------------------------------------------------------------------------
如果你觉得文章有用,欢迎打赏
All posts unless otherwise mentioned are licensed under
Any source code unless otherwise mentioned is licensed under the 3 clause BSD license
标签:count,10,Code,seq,buffer,2015 From: https://www.cnblogs.com/z-cm/p/17088327.html