最近第二遍看Google's Python Class,發(fā)現(xiàn)還是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里面谣辞,不能把字符串和數(shù)字用+直接連接迫摔,否則會得到TypeError: cannot concatenate 'str' and 'int' objects
錯誤,需要用str()函數(shù)把count數(shù)字轉為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.
根據(jù)原題提供的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