Writing-Function-in-Python

1. Best Practices

1.1 Docstrings

1.2 Crafting a docstring

You’ve decided to write the world’s greatest open-source natural language processing Python package. It will revolutionize working with free-form text, the way numpy did for arrays, pandas did for tabular data, and scikit-learndid for machine learning.

The first function you write is count_letter(). It takes a string and a single letter and returns the number of times the letter appears in the string. You want the users of your open-source package to be able to understand how this function works easily, so you will need to give it a docstring. Build up a Google Style docstring for this function by following these steps.

Instruction 1
Copy the following string and add it as the docstring for the function: Count the number of times letter appears in content.

在这里插入代码片

Instruction 2
Now add the arguments section, using the Google style for docstrings. Use str to indicate a string.

在这里插入代码片

Instruction 3
Add a returns section that informs the user the return value is an int.

在这里插入代码片

Instruction 4
Finally, add some information about the ValueError that gets raised when the arguments aren’t correct.

在这里插入代码片

1.3 Retrieving docstrings

You and a group of friends are working on building an amazing new Python IDE (integrated development environment – like PyCharm, Spyder, Eclipse, Visual Studio, etc.). The team wants to add a feature that displays a tooltip with a function’s docstring whenever the user starts typing the function name. That way, the user doesn’t have to go elsewhere to look up the documentation for the function they are trying to use. You’ve been asked to complete the build_tooltip() function that retrieves a docstring from an arbitrary function.

Note that in Python, you can pass a function as an argument to another function. I’ll talk more about this in chapter 3, but it will be useful to keep in mind for this exercise.

Instruction 1
Begin by getting the docstring for the function count_letter(). Use an attribute of the count_letter() function.

在这里插入代码片

Instruction 2
Now use a function from the inspect module to get a better-formatted version of count_letter()'s docstring.

在这里插入代码片

Instruction 3
Use the inspect module again to get the docstring for any function being passed to the build_tooltip() function.

在这里插入代码片

1.4 Docstrings to the rescue!

Some maniac has corrupted your installation of numpy! All of the functions still exist, but they’ve been given random names. You desperately need to call the numpy.histogram() function and you don’t have time to reinstall the package. Fortunately for you, the maniac didn’t think to alter the docstrings, and you know how to access them. numpy has a lot of functions in it, so we’ve narrowed it down to four possible functions that could be numpy.histogram() in disguise: numpy.leyud(), numpy.uqka(), numpy.fywdkxa() or numpy.jinzyxq().

Examine each of these functions’ docstrings in the IPython shell to determine which of them is actually numpy.histogram().

□ \square numpy.leyud()
□ \square numpy.uqka()
■ \blacksquare numpy.fywdkxa()
□ \square numpy/jinzyxq()

1.5 DRY and “Do One Thing”

1.6 Extract a function

While you were developing a model to predict the likelihood of a student graduating from college, you wrote this bit of code to get the z-scores of students’ yearly GPAs. Now you’re ready to turn it into a production-quality system, so you need to do something about the repetition. Writing a function to calculate the z-scores would improve this code.

# Standardize the GPAs for each year
df['y1_z'] = (df.y1_gpa - df.y1_gpa.mean()) / df.y1_gpa.std()
df['y2_z'] = (df.y2_gpa - df.y2_gpa.mean()) / df.y2_gpa.std()
df['y3_z'] = (df.y3_gpa - df.y3_gpa.mean()) / df.y3_gpa.std()
df['y4_z'] = (df.y4_gpa - df.y4_gpa.mean()) / df.y4_gpa.std()

Instruction

  • Finish the function so that it returns the z-scores of a column.
  • Use the function to calculate the z-scores for each year (df['y1_z'], df['y2_z'], etc.) from the raw GPA scores (df.y1_gpa, df.y2_gpa, etc.).
在这里插入代码片

Split up a function

Another engineer on your team has written this function to calculate the mean and median of a list. You want to show them how to split it into two simpler functions: mean() and median()

def mean_and_median(values):
  """Get the mean and median of a list of `values`

  Args:
    values (iterable of float): A list of numbers

  Returns:
    tuple (float, float): The mean and median
  """
  mean = sum(values) / len(values)
  midpoint = int(len
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值