Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

New coding contest

Name: Anonymous 2009-11-28 15:49

We haven't had one in a while so let's have a new coding contest. I'm open to suggestions for the challenge, but if we don't have any good suggestions we will default to something stupid like "implement cowsay in erlang shitty language X".

Name: Leah Culver !1LEahRIBg. 2009-11-29 18:49

Here is a nearly complete version of cowsay implemented in python, although it differs slightly from the original.
* It doesn't support cowthink (although this shouldn't be difficult to add).
* The help returned by -h is sparse and the docstrings non-existant.
* It doesn't support the -l flag which displays the COWPATH as I don't support cowfiles.
* The -f flag opens up a regular file and uses that as a message, whereas the original uses a cowfile instead.
* It keeps the bug/feature of the original in that you can pass in a 1 character tongue string or eye string.
 I'm sure there are others and bugs that I haven't found(well, I didn't do any unit tests ;), but there you go. Before you ask, the code is ugly, because I'm lazy and didn't really give a shit.

from optparse import OptionParser
from collections import namedtuple

def chunks(s,n):
    l = []
    while len(s) > n:
        l.append(s[:n])
        s = s[n:]
    l.append(s)
    return l

def strip_extra_whitespace(s):
    l = []
    prev = False
    for c in s:
        if c.isspace():
            if prev:
                continue
            prev = True
        else:
            prev = False
        l.append(c)
    return "".join(l)

CowType = namedtuple('Cowtype','eyes tongue')

class Cow():
    template = """
        \\   ^__^
         \\  (%s)\\_______
            (__)\       )\\/\\
             %s ||----w |
                ||     ||"""

    cowtypes = {"normal" : CowType("oo","  "),
            "borg" : CowType("==","  "),
            "dead" : CowType("XX","U "),
            "greedy" : CowType("$$","  "),
            "paranoid" : CowType("@@","  "),
            "stoned" : CowType("**","U "),
            "tired" : CowType("--","  "),
            "wired" : CowType("OO","  "),
            "youthful" : CowType("..","  ")}

    def __init__(self,words,type="normal",wrap=40):
        self.words = self.generate_speech(words,wrap=wrap)
        self.eyes,self.tongue = self.cowtypes[type]
    def __repr__(self):
        global templates
        return self.words + self.template % (self.eyes,self.tongue)
    def generate_speech(self,s,wrap=False):
        if wrap:
            lines =  chunks(strip_extra_whitespace(s.replace("\n"," ").replace("\t",4 * " ")),wrap)
        else:
            lines =  s.replace("\t",4*" ").splitlines()
        maxlen =  max(map(len,lines))
        toplines = [" " + "_"*(maxlen+2)]
        bottomlines = [" " + "-"*(maxlen + 2)]
        if len(lines) == 1:
            lines[0] = "< %s >" % lines[0]
        else:
            for i in range(len(lines)):
                if i == 0:
                    delimiters = "/","\\"
                elif i == len(lines)-1:
                    delimiters = "\\","/"
                else:
                    delimiters = "|","|"

                lines[i] = "%s %s%s %s" % (delimiters[0],lines[i], (maxlen-len(lines[i])) * " ",delimiters[1])
        return "\n".join(toplines + lines + bottomlines)

def make_parser():
    parser = OptionParser()
    parser.add_option("-e",dest="eye_string")
    parser.add_option("-f",dest="file")
    parser.add_option("-n",dest="whitespace",action="store_true",default=False)
    parser.add_option("-T",dest="tongue_string")
    parser.add_option("-W",dest="column",type="int",action="store")

    parser.set_defaults(cowtype="normal")
    parser.add_option("-b",dest="cowtype",action="store_const",const="borg")
    parser.add_option("-d",dest="cowtype",action="store_const",const="dead")
    parser.add_option("-g",dest="cowtype",action="store_const",const="greedy")
    parser.add_option("-p",dest="cowtype",action="store_const",const="paranoid")
    parser.add_option("-s",dest="cowtype",action="store_const",const="stoned")
    parser.add_option("-t",dest="cowtype",action="store_const",const="tired")
    parser.add_option("-w",dest="cowtype",action="store_const",const="wired")
    parser.add_option("-y",dest="cowtype",action="store_const",const="youthful")

    return parser

if __name__ == "__main__":
    import sys
    parser = make_parser()
    (options,args) = parser.parse_args()
    if options.file:
        try:
            f = open(options.file)
            message = f.read()
            f.close()
        except IOError:
            sys.stderr.write("File %s not found\n" % options.file)
            sys.stderr.flush()
            sys.exit(1)
           
    elif args:
        message = " ".join(args)
    else:
        message = sys.stdin.read()

    if options.whitespace:
        wrap = False
    elif options.column:
        wrap = options.column
    else:
        wrap = 40

    cow = Cow(message,options.cowtype,wrap)
    if options.eye_string:
        cow.eyes = options.eye_string[:2]
    if options.tongue_string:
        cow.tongue = options.tongue_string[:2]

    print cow

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List