每周练习-20180724

这篇是前两天写好的,今天放上来

'''
Description:
A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.

Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.

###Arguments (Haskell)

First argument: space-delimited list of minor words that must always be lowercase except for the first word in the string.
Second argument: the original string to be converted.
###Arguments (Other languages)

First argument (required): the original string to be converted.
Second argument (optional): space-delimited list of minor words that must always be lowercase except for the first word in the string. The JavaScript/CoffeeScript tests will pass undefined when this argument is unused.
###Example

title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings'
title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows'
title_case('the quick brown fox') # should return: 'The Quick Brown Fox'

简单翻译:
将给定的第一个参数(字符串),如果首字母不是大写的就将他设为大写。第二个参数给定的单词如果出现在字符串中,则看是不是句首,
如果不位于句首则直接替换。
'''

 

自己

'''
解题思路:
1、挺傻的先处理了第一个参数为空字符串,以及第二个参数为空的情况
2、如果两个参数都不为空,则用空格切分字符串,依次大写首字母
3、判断第二个参数是否出现在字符串中,如果出现,则看出现在哪个位置,如果不在句首就直接替换
'''
def title_case(title, minor_words=None):
    if not title:
        return title
    if not minor_words:
        return ' '.join(map(lambda s: s.capitalize(), title.split(' ')))
    else:
        return find_str(list(map(lambda s: s.capitalize(), title.split(' '))), minor_words)


def find_str(l, string):
    old = l
    new = [i.lower() for i in l]
    string = string.split(' ')
    for s in string:
        for i in range(len(new)):
            if s.lower() == new[i]:
                if i != 0:
                    old[i] = s.lower()
    return ' '.join(old)

 

他人

'''
值得学习的地方:
英语差还是有太多坑要踩,题意和我理解的其实有一点出入...
1、首先将字符串的句首词大写,其他单词小写
2、然后将第二个参数的全部单词小写
3、这是最关键的一步,使用了列表解析器和三元表达式,如果第二个参数的单词在字符串中,则直接输出单词,如果没出现则将该单词大写
'''
def title_case(title, minor_words=''):
    title = title.capitalize().split()
    minor_words = minor_words.lower().split()
    return ' '.join([word if word in minor_words else word.capitalize() for word in title])

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值