Checkio - What does the cow say? 题目和答案

What does the cow say?

Lets cow say!

Our cow is young and can only say some of the words we teach it. Not only does it talk, but this cow can turn into the famous Tux (wiki/Cowsay) if we ask it nicely.

You are given some text and your function should format it in the "cows" speech. Let's examine the rules for this problem:
  • The cow is always the same, only quote changes.
  • Multiple spaces in a row are replaced by one space.
  • The top border consists of underscore characters. It starts from a single space and ends before the border column.
  • Each line of the quote consists of these parts: quote border(1), space(1), line(1-39), space(1), quote border(1).
  • If line is less than 40 characters, it will fit into one string. The string is quoted in <>.
  • If the line is greater than or equal to 40 characters, it should be split by these rules:
    • Max line size is 39 chars. If any spaces are in the line, split it by the rightmost space (this space is removed from text) otherwise take the first 39 characters.
    • After the split align all lines to same length by adding spaces at the end of each line.
    • First line borders: /\
    • Middle line borders: ||
    • Last line borders: \/
  • The bottom border consists of the minus sign. Has same length as top.
  • cowsay console program has strange behavior in certain cases, this cases will not be tested here.
     _________________________________
    / Dog goes woof                   \
    | Cat goes meow                   |
    | Bird goes tweet                 |
    | And mouse goes squeek           |
    | Cow goes moo                    |
    | Duck goes quack                 |
    \ And the solution will go to you /
     ---------------------------------
            \   ^__^
             \  (oo)\_______
                (__)\       )\/\
                    ||----w |
                    ||     ||
    
What does the cow say?

Input: Text as a string.

Output: The result for the console as a string.

Hint: Read python docs (2.73.3) about formatting styles (str.format and %). Notice for r before the string. It is a raw string and they use different rules for interpreting backslash escape sequences.

How it is used: The original Cowsays are written in the Perl programming language, and as such are easily adaptable to system tasks in Unix. They can perform functions such as telling users their home directories are full, that they have new mail, etc. Now you will write your own realisation for this classic unix program. This concept can teach you how to prepare and format text for the console output.

Precondition: 0 < len(text) < 858;
text contains at least last non-space character;
text contains only ASCII letters, digits and punctuation.


这题花费我大量时间 不过也学到了不少 用到了<span style="font-family: Arial, Helvetica, sans-serif;">re.split等 不过写得很复杂 很乱...</span>
import re
def cowsay(words):
    l=re.split("\s+",words) 
    cutl=[""]*(len(l)+20)
    j=0
    out = "\n"
    print l
    for i in l:
        if len(cutl[j])+len(i)<40:
            cutl[j]+=i
            cutl[j]+=' '
        elif len(i)>=40:
            if j!=0:
                j+=1
            while len(i)>=40:
                cutl[j]= cutl[j]+i[:39]+' '
                i=i[39:]
                j+=1
            cutl[j]= cutl[j]+i[:39]+' '
        else:
            j+=1
            cutl[j]+=i
            cutl[j]+=' '
    print cutl
    lenl=sorted(cutl,key=lambda x:len(x),reverse=True)
    maxlen=len(lenl[0])
    for i in range(len(cutl)):
        if len(cutl[i])>=2 and len(cutl[i])==maxlen and cutl[i][-2]==' ':
            cutl[i] = cutl[i][0:-1]
    print cutl
    maxlen=len(lenl[0])
    out= out + " "+(maxlen+1)*'_'+"\n"
    if len(lenl[1]) == 0:
        out = out +"< "+cutl[0]+(maxlen-len(cutl[0]))*' '+">"+"\n"
    else:
        for i in range(len(cutl)):
            if len(cutl[i])==0:
                break
            if i == 0:
                out = out +"/ "+cutl[i]+(maxlen-len(cutl[i]))*' '+"\\"+"\n"
            elif len(cutl[i+1]) == 0:
                out = out +"\ "+cutl[i]+(maxlen-len(cutl[i]))*' '+"/"+"\n"
                break
            else:
                out = out +"| "+cutl[i]+(maxlen-len(cutl[i]))*' '+"|"+"\n"
    out= out + " "+(maxlen+1)*'-'+"\n"
    out+= "        \   ^__^\n"
    out+= "         \  (oo)\_______\n"
    out+= "            (__)\       )\/\\\n"
    out+= "                ||----w |\n"
    out+= "                ||     ||\n"
    print out
    return out



下面是我看到的一个较好的版本:

import re
from functools import reduce
 
COW = r'''
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
'''
def cowsay(text):
    lst = re.findall(r'''(?x) (?P<cut> [^\s]{39} ) \s?
                     | (?= ( .{1,39} ) (?: \s | $ ) ) \2 \s?''',
                    re.sub(r'\s+', r' ', text))
    lst = [ match for el in lst for match in el if match ]
    just = max(len(s) for s in lst)
    lst = list(map(lambda s: s.ljust(just), lst))
    forms = [ '< {0} >\n' ] if len(lst) == 1 else \
            [ '/ {0} \\\n' ] + [ '| {0} |\n' ]*(len(lst)-2) + ['\\ {0} /\n' ]
    res = ['\n '+(just+2)*'_'+'\n'] + \
            [fmt.format(el) for (fmt, el) in zip(forms, lst)] + [' '+(just+2)*'-']
    return reduce(lambda acc,v: acc + v, res, '') + COW


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值