Python: Python Google Class 习题分析一

最近第二遍看Google's Python Class,发现还是Google的大牛比较厉害,写的很简短,但是写的很清楚明了,给的题目也很有针对性,下面是我对题目的一些分析,仅作笔记之用。
1

# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5'
# and donuts(23) returns 'Number of donuts: many'

本题比较简单,仅需判断string的长度,唯一需要注意的是,在Python里面,不能把字符串和数字用+直接连接,否则会得到TypeError: cannot concatenate 'str' and 'int' objects错误,需要用str()函数把count数字转为string类型。
参考代码:

def donuts(count):
    if(count>=10):
        str1 = "Number of donuts: many"
    else:
        str1 = "Number of donuts: " + str(count)
    return str1

2

# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.

本题主要是使用Python string的slice,对于字符串s而言,开始两个字符是是s[0:2]或者就简单的表示为[:2], 最后两个字符是s[-2:]
参考代码:

def both_ends(s):
    if len(s) <= 2:
        return ''
    else:
        return s[0:2] + s[-2:]

3

# C. fix_start
# Given a string s, return a string
# where all occurences of its first char have
# been changed to '*', except do not change
# the first char itself.
# e.g. 'babble' yields 'ba**le'
# Assume that the string is length 1 or more.
# Hint: s.replace(stra, strb) returns a version of string s
# where all instances of stra have been replaced by strb.

根据原题提供的hint,主要是要使用replace方法去替换字符串,然后生成题目要求的字符串.

def fix_start(s):
    if len(s) > 1:
    return s[0] + s[1:].replace(s[0], "*")

4

# D. MixUp
# Given strings a and b, return a single string with a and b separated
# by a space '<a> <b>', except swap the first 2 chars of each string.
# e.g.
#   'mix', pod' -> 'pox mid'
#   'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or more.

本题使用的也是string的slice

def mix_up(a, b):
    if len(a) >=2 and len(b)>=2:
        str1 = b[0:2] + a[2:]
        str2 = a[0:2] + b[2:]
        return str1 + " " + str2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容