检查字符串的平均字符是否在Python中存在


假设我们有一个包含字母数字字符的字符串s,我们需要检查字符串的平均字符是否存在,如果存在则返回该字符。这里的平均字符可以通过取s中每个字符ASCII值的平均值的向下取整来找到。

因此,如果输入类似于s = “pqrst”,则输出将是'r',因为字符ASCII值的平均值为(112 + 113 + 114 + 115 + 116)/5 = 570/5 = 114 (r)。

为了解决这个问题,我们将遵循以下步骤:

  • total := 0
  • 对于s中的每个字符ch,执行:
    • total := total + ch的ASCII值
  • avg := (total / s的长度)的向下取整
  • 返回ASCII值为avg的字符

让我们来看下面的实现来更好地理解:

示例代码

在线演示

from math import floor
def solve(s):
   total = 0
 
   for ch in s: 
      total += ord(ch)
 
   avg = int(floor(total / len(s)))
 
   return chr(avg)

s = "pqrst"
print(solve(s))

输入

"pqrst"

输出

r

更新于:2021年1月16日

86 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.