最近第二遍看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類型。
參考代碼:
1 def donuts(count):2 if(count>=10):3 str1 = "Number of donuts: many"4 else:5 str1 = "Number of donuts: " + str(count)6 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:]
參考代碼:
1 def both_ends(s):2 if len(s) <= 2:3 return ''4 else:5 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方法去替換字串,然後產生題目要求的字串
參考代碼:
1 def fix_start(s):2 if len(s) > 1:3 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
參考代碼:
1 def mix_up(a, b):2 if len(a) >=2 and len(b)>=2:3 str1 = b[0:2] + a[2:]4 str2 = a[0:2] + b[2:]5 return str1 + " " + str2