Python Google Class 習題分析一

來源:互聯網
上載者:User

最近第二遍看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

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.