python join(), bool(), strip(), dict()

Question:

Stephen's speech module is broken. Thismodule is responsible for his number pronunciation. He has to click to inputall of the numerical digits in a figure, so when there are big numbers it cantake him a long time. Help the robot to speak properly and increase his numberprocessing speed by writing a new speech module for him. All the words in thestring must be separated by exactly one space character. Be careful with spaces-- it's hard to see if you place two spaces instead one.

Input: A number as an integer.

Output: The string representation ofthe number as a string.

How it is used: This concept may beuseful for the speech synthesis software or automatic reports systems. Thissystem can also be used when writing a chatbot by assigning words or phrasesnumerical values and having a system retrieve responses based on those values.

Precondition: 0 < number < 1000

 

Code:

方法一:

FIRST_TEN = ["zero", "one", "two", "three", "four", "five", "six", "seven",
             "eight", "nine"]
SECOND_TEN = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
              "sixteen", "seventeen", "eighteen", "nineteen"]
OTHER_TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
              "eighty", "ninety"]
HUNDRED = "hundred"
​
​
def checkio(number):
    hundreds = number/100
    tens = number%100/10
    ones = number%10
    res = []
    
    if hundreds:
        res.extend ((FIRST_TEN[hundreds], 'hundred'))
    if tens:
        if tens==1:
            res.append (SECOND_TEN[ones])
        else:
            res.append (OTHER_TENS[tens])
    if ones and tens!=1:
        res.append (FIRST_TEN[ones])
    
    return ' '.join(res)



方法二:

FIRST_TEN = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
SECOND_TEN = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
OTHER_TENS = ["", "", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety "]
​
def checkio(number):
    return ' '.join(['%s hundred' % FIRST_TEN[(number/100)]*(number>=100), (SECOND_TEN[number%10] if 10<=number%100<=19 else OTHER_TENS[(number/10)%10] + FIRST_TEN[number%10]*(number>0))]).strip()

 

方法三:

def checkio(n):
    w, h, t, o = (",one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve," + 
                   "thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,,," +
                   "twenty ,thirty ,forty ,fifty ,sixty ,seventy ,eighty ,ninety ," +
                   " hundred ").split(","), n / 100, (n % 100) / 10, n % 10
    return     (w[h] + w[30] * bool(h) + w[t + 20] + w[o + 10 * (t == 1)]).strip()


 check:

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio(4) == 'four', "1st example"
    assert checkio(133) == 'one hundred thirty three', "2nd example"
    assert checkio(12) == 'twelve', "3rd example"
    assert checkio(101) == 'one hundred one', "4th example"
    assert checkio(212) == 'two hundred twelve', "5th example"
    assert checkio(40) == 'forty', "6th example"
    assert not checkio(212).endswith(' '), "Don't forget strip whitespaces at the end of string"



扩展:

1. join:       字符串操作函数,操作的也是字符串,其作用结合字符串使用,常常用于字符连接操作, 将()内按指定字符连接。括号内必须是一个对象。如果有多个就写成元组,或是列表。

>>> a="abcd"
>>> ",".join(a)
'a,b,c,d'
>>> "|".join(['a','b','c'])
'a|b|c'
>>> ",".join(('a','b','c'))
'a,b,c'
>>> ",".join({'a':1,'b':2,'c':3})
'a,c,b'

要保证a,b等的整体性,就必须用元组,否则会按每个字符分开,a,b内部也会被分开:

>>> k1="ttt"
>>> k2="sss"
>>> a=k1+k2
>>> ",".join(a)
't,t,t,s,s,s'

 

 

2. bool():x转换为Boolean类型,如果x缺省,返回Falsebool也为int的子类

Python中除了''""0()[]{}NoneFalse之外,其他的都是True。也就是说上面的'False'就是一个不为空的字符串,所以结果就为True了。

为了深入了解下Pythonbool类型,就看了下说明:

>>>help(True)
Help on bool object:

class bool(int)
|  bool(x) -> bool
|  

|  Returns True when the argument x is true, False otherwise.
|  The builtins True and False are the only two instances of the class bool.
|  The class bool is a 
subclass of the class int, and cannot besubclassed.
|  

|  Method resolution order:
|      bool
|      int
|      object
|  
|  Methods defined here:
|  
|  __and__(...)
|      x.__and__(y) <==> x&y
|  
|  __or__(...)
|      x.__or__(y) <==> x|y

可以看到boolint的子类来的,并且不可以子类化:

因为boolint的子类,所以用1表示True0表示False

 

 

3. str.strip([chars]):     用于移除字符串头尾指定的字符(默认为空格)

       参数:chars -- 移除字符串头尾指定的字符

返回值:返回移除字符串头尾指定的字符生成的新字符串。

str.strip(rm)       删除字符串中开头、结尾处,位于 rm删除序列的字符

str.lstrip(rm)      删除字符串中开头处,位于 rm删除序列的字符

str.rstrip(rm)     删除字符串中结尾处,位于 rm删除序列的字符

注意:当rm为空时,默认删除空白符(包括'\n','\r',  '\t',  ' '


4. dict(zip(a,b)): 从两个list构造dictionary

>>>FIRST_TEN = ["one", "two", "three", "four", "five", "six", "seven",
             "eight", "nine"]
>>>FIRST_TEN_DIGIT = [i for i in range(1, 10)]
>>>TEN = dict(zip(FIRST_TEN_DIGIT, FIRST_TEN))



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值