Skip to content

Instantly share code, notes, and snippets.

@jkeesh
Created September 29, 2013 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkeesh/6748788 to your computer and use it in GitHub Desktop.
Save jkeesh/6748788 to your computer and use it in GitHub Desktop.
Look and Say
import sys
SENTINEL = -1
def lookandsay(num):
"""Return the look and say version of num."""
num = str(num)
cur_digit = SENTINEL
cur_streak = 0
result = ""
for cur in num:
if cur == cur_digit or cur_digit == SENTINEL:
cur_streak += 1
else:
result += str(cur_streak)
result += str(cur_digit)
cur_streak = 1
cur_digit = cur
result += str(cur_streak)
result += str(cur_digit)
return result
def lookandsay_sequence(num_items):
"""Print the first num_items of the look an say sequence."""
cur = 1
for i in range(num_items):
print cur
cur = lookandsay(cur)
if __name__ == "__main__":
if len(sys.argv) > 1:
print lookandsay(sys.argv[1])
else:
lookandsay_sequence(10)
@econner
Copy link

econner commented Sep 29, 2013

Nice. Pretty sure this works.

Here is mine:

def look_and_say(digits):
    outStr = ""

    if not digits:
        return outStr

    curChar = nextChar = digits[0]
    runLen = 1

    for digit in digits[1:]:
        nextChar = digit

        if nextChar == curChar:
            runLen += 1
        else:
            outStr += "%s%s" % (runLen, curChar)
            curChar = nextChar
            runLen = 1

    if nextChar == curChar:
        outStr += "%s%s" % (runLen, curChar)
    return outStr


assert "121325" == look_and_say("2355")
assert "12" == look_and_say("2")
assert "12431443" == look_and_say("2333343333")
assert "" == look_and_say("")
assert "32" == look_and_say("222")
assert "10" == look_and_say("0")
assert "121314121314252719" == look_and_say("23423455779")

Also can you make this private?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment