首页 > 解决方案 > 如何确定函数中使用多少个参数

问题描述

我是 Python 新手,一直在尝试从 Codeacademy 学习 Python。这是我在此的头一篇博文。

这是 Codeacademy 给出的示例代码(答案)。

proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself", "Helena"]

def censor_two(input_text, censored_list):
  for word in censored_list:
    censored_word = ""
    for x in range(0,len(word)):
      if word[x] == " ":
        censored_word = censored_word +" "
      else:
        censored_word = censored_word + "X"
    input_text = input_text.replace(word, censored_word)
  return input_text

print(censor_two(email_two, proprietary_terms)) 

以上面的代码为例,我怎么知道我需要 2 个参数?这里 input_text,censored_list。

这是问题:

Write a function that can censor not just a specific word or phrase from a body of text, but a whole list of words and phrases, and then return the text.

Mr. Cloudy has asked that you censor all words and phrases from the following list in email_two.

proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]

我必须查看答案才能了解如何解决问题。但是对于我的第一次尝试,我不知道要在函数中放入多少参数,也无法解决它:[

是否有一些规则或指导方针可以了解函数需要多少参数?

例如下一个问题:

The most recent email update has concerned Mr. Cloudy, but not for the reasons you might think. He tells you, “this is too alarmist for the Board of Investors! Let’s tone down the negative language and remove unnecessary instances of ‘negative words.’”

Write a function that can censor any occurance of a word from the “negative words” list after any “negative” word has occurred twice, as well as censoring everything from the list from the previous step as well and use it to censor email_three.

negative_words = ["concerned", "behind", "danger", "dangerous", "alarming", "alarmed", "out of control", "help", "unhappy", "bad", "upset", "awful", "broken", "damage", "damaging", "dismal", "distressed", "distressed", "concerning", "horrible", "horribly", "questionable"]

我认为它需要3个参数?这是我的猜测,因为上一个问题需要 2 个(1 个用于电子邮件,1 个用于单词列表),现在有 2 个列表和 1 个电子邮件,所以我猜它需要 3 个参数?

但是对于其他功能和其他类型的问题..您如何确定它需要多少参数?提前非常感谢。我希望我的问题很清楚。

标签: pythonloopsif-statementquotation-marks

解决方案


我认为您应该以这种方式处理它。函数只是一些黑匣子,它接收一些输入并吐出所需的输出。输入是参数,输出是它返回的审查文本。让我们看一个例子。假设您被要求计算两个数字的平均值。为了清楚起见,您命名的函数find_average需要两个数字来计算它们的平均值。这些是你的参数。如果您感到困惑,只需绘制一些随机框并考虑输出和产生该输出所必需的输入列表。在你的最后一个问题中你是对的,你需要 3 个输入(参数)来完成你被问到的事情。你的任务是审查文本。现在让我们列出完成该任务所需的内容。

  1. 首先,您需要审查该文本
  2. 那么你需要一份清单negative words
  3. 最后你需要清单proprietary_terms

使用上述输入,您需要按照说明生成一个干净的审查文本。这意味着您需要三个参数用于特定的审查功能。

我希望这能澄清你的困境。

以及一点提示:在理解问题之前不要急于编写函数。您应该首先使用一些示例输入和提供的约束来解决您的问题。


推荐阅读