Skip to content

Instantly share code, notes, and snippets.

@codian
Last active August 29, 2015 14:17
Show Gist options
  • Save codian/dbfd3b6a0ef09b2d39ec to your computer and use it in GitHub Desktop.
Save codian/dbfd3b6a0ef09b2d39ec to your computer and use it in GitHub Desktop.
Look and Say
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
import re
r = re.compile('((\d)\\2*)')
s = '1'
print s
for _ in range(50):
s = ''.join([''.join([str(len(m[0])), m[0][0]]) for m in r.findall(s)])
print s
#=> python las.py 3.24s user 0.22s system 43% cpu 7.889 total
# Python 2.7.6
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'stringio'
r = /((\d)\2*)/
puts '1'
(2..50).inject('1') do |i, n|
seq = i.scan(r).inject(StringIO.new) do |s, m|
s << m[0].length.to_s << m[0][0]
end
puts seq.string
seq.string
end
#=> ruby las.rb 2.96s user 0.12s system 54% cpu 5.642 total
# ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'stringio'
puts '1'
(2..50).inject('1') do |input, n|
seq = StringIO.new
last = nil
count = 0
input.each_char do |char|
if last == char
count += 1
next
end
if not last.nil?
seq.write(count)
seq.write(last)
end
last = char
count = 1
end
if not last.nil?
seq.write(count)
seq.write(last)
end
puts seq.string
seq.string
end
#=> ruby las_2.rb 1.64s user 0.05s system 49% cpu 3.418 total
# ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment