Check whether the Average Character of the String is present or not in Python

Suppose we have a string s that contains alphanumeric characters, we have to check whether the average character of the string is present or not, if yes then return that character. Here the average character can be found by taking floor of average of each character ASCII values in s.

So, if the input is like s = “pqrst”, then the output will be 'r' because the average of character ASCII values are (112 + 113 + 114 + 115 + 116)/5 = 570/5 = 114 (r).

To solve this, we will follow these steps −

  • total := 0
  • for each ch in s, do
    • total := total + ASCII of ch
  • avg := the floor of (total / size of s)
  • return character from ASCII avg

Let us see the following implementation to get better understanding −

Example Code

Live Demo

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"