鱼C论坛

 找回密码
 立即注册
查看: 2297|回复: 4

[已解决]关于python中的函数问题

[复制链接]
发表于 2021-6-24 10:47:58 | 显示全部楼层 |阅读模式
3鱼币
我想写两个函数,并且通过下面的测试,请大家帮帮忙

问题一:编写一个函数 one_word(words),它接收字符串列表并使用 for... in... 循环将所有单词连接到一个字符串中(即“correcthorsebatterystaple”)。
测试:
words = ["correct", "horse", "battery", "staple"]
assert(one_word(words)=="correcthorsebatterystaple")

问题二:
编写一个函数 as_and_es(words),它使用循环计算 2𝑎+𝑒,其中 𝑎 是字母“a”在所有单词中出现的次数,而 𝑒 是字母“e”出现的次数。
测试:
words = ["correct", "horse", "battery", "staple"]
assert(as_and_es(words)==8)

最佳答案
2021-6-24 10:47:59
  1. words = ["correct", "horse", "battery", "staple"]
  2. def one_word(words):
  3.     a = ''
  4.     for i in words:
  5.         a += i
  6.     return a

  7. def as_and_es(words):
  8.     b = one_word(words)
  9.     x = 0
  10.     y = 0
  11.     for j in b:
  12.         if j == 'a':
  13.             x += 1
  14.         elif j == 'e':
  15.             y += 1
  16.     sum = 2 * x + y
  17.     return sum
  18. print(one_word(words))
  19. print(as_and_es(words))
复制代码

最佳答案

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-6-24 10:47:59 | 显示全部楼层    本楼为最佳答案   
  1. words = ["correct", "horse", "battery", "staple"]
  2. def one_word(words):
  3.     a = ''
  4.     for i in words:
  5.         a += i
  6.     return a

  7. def as_and_es(words):
  8.     b = one_word(words)
  9.     x = 0
  10.     y = 0
  11.     for j in b:
  12.         if j == 'a':
  13.             x += 1
  14.         elif j == 'e':
  15.             y += 1
  16.     sum = 2 * x + y
  17.     return sum
  18. print(one_word(words))
  19. print(as_and_es(words))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-6-24 10:50:27 | 显示全部楼层
重发帖吧,3个鱼币还不如不悬赏

而且这是个大活
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-6-24 10:56:15 | 显示全部楼层
  1. def one_word(words):
  2.       return "".join(words)

  3. def as_and_es(words):
  4.       word = "".join(words)
  5.       return 2 * word.count("a") + word.count("e")
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-6-24 11:04:06 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 09:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表