I recently read Google's Python Class for the second time and found that Google is still a good guy. I wrote it very briefly, but it was very clear and specific, the following is my analysis of the question, which is only used for notes.
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 'authorization'
# Instead of the actual count.
# So donuts (5) returns 'number of donuts: 5'
# And donuts (23) returns 'number of donuts: done'
This article is relatively simple. You only need to judge the length of the string. The only thing you need to note is that in Python, strings and numbers cannot be directly connected with +; otherwise, TypeError is returned: cannot concatenate 'str' and 'int' objects is incorrect. You need to use the str () function to convert the count number to the string type.
Reference code:
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 'ields 'spng '. However, if the string length
# Is less than 2, return instead the empty string.
This article mainly uses slice of Python string. For string s, the first two characters are s [0: 2] or simply [: 2]. the last two characters are s [-2:]
Reference code:
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 '*', does t 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.
According to the hint provided by the original question, the replace method is used to replace the string and generate the string required by the question.
Reference code:
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>', using t 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.
This topic uses a string slice.
Reference code:
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